ingest_csv.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210
  1. #!/usr/bin/env python3
  2. #ident "@(#)$Format:LocalFoodAI:ingest_csv.py:%an:%ae:%ad:%cn:%ce:%cd:%H:%D:%N$"
  3. import pandas as pd
  4. import myloginpath
  5. import urllib.parse
  6. from sqlalchemy import create_engine, text
  7. from sqlalchemy.types import VARCHAR, DOUBLE
  8. from sqlalchemy.dialects.mysql import LONGTEXT
  9. import os
  10. import sys
  11. from snmp_notifier import notifier
  12. def get_loader_engine():
  13. try:
  14. import os
  15. db_host = os.environ.get('DB_HOST')
  16. db_user = os.environ.get('DB_USER')
  17. db_pass = os.environ.get('DB_PASS')
  18. if db_host and db_user and db_pass:
  19. password = urllib.parse.quote_plus(db_pass)
  20. conn_str = f"mysql+pymysql://{db_user}:{password}@{db_host}/food_db?charset=utf8mb4"
  21. return create_engine(conn_str)
  22. conf = myloginpath.parse('app_loader')
  23. user = conf.get('user')
  24. password = urllib.parse.quote_plus(conf.get('password'))
  25. host = conf.get('host', '127.0.0.1')
  26. database = 'food_db'
  27. conn_str = f"mysql+pymysql://{user}:{password}@{host}/{database}?charset=utf8mb4"
  28. return create_engine(conn_str)
  29. except Exception as e:
  30. print(f"❌ Failed to parse myloginpath or create engine: {e}")
  31. sys.exit(1)
  32. def init_ingestion_status_table(engine):
  33. with engine.begin() as conn:
  34. conn.execute(text("""
  35. CREATE TABLE IF NOT EXISTS ingestion_status (
  36. id INT AUTO_INCREMENT PRIMARY KEY,
  37. filename VARCHAR(255),
  38. start_time DATETIME,
  39. end_time DATETIME,
  40. rows_loaded INT,
  41. status VARCHAR(50),
  42. error_message TEXT
  43. )
  44. """))
  45. def ingest_file(filename, engine):
  46. if not os.path.exists(filename):
  47. print(f"File {filename} not found locally.")
  48. return False
  49. print(f"\n🚀 Found {filename}! Starting grouped vertical partition ingestion...")
  50. chunk_size = 10000
  51. total_processed = 0
  52. max_chunks = int(os.environ.get('MAX_CHUNKS', '0'))
  53. chunks_count = 0
  54. # Define the groupings
  55. groups = {
  56. 'products_core': [
  57. 'code', 'product_name', 'generic_name', 'brands', 'ingredients_text',
  58. 'url', 'image_url', 'image_small_url', 'image_ingredients_url',
  59. 'image_ingredients_small_url', 'image_nutrition_url', 'image_nutrition_small_url'
  60. ],
  61. 'products_allergens': ['code', 'allergens'],
  62. 'products_macros': ['code', 'energy-kcal_100g', 'proteins_100g', 'fat_100g', 'carbohydrates_100g', 'sugars_100g', 'fiber_100g', 'sodium_100g', 'salt_100g', 'cholesterol_100g'],
  63. 'products_vitamins': ['code', 'vitamin-a_100g', 'vitamin-b1_100g', 'vitamin-b2_100g', 'vitamin-pp_100g', 'vitamin-b6_100g', 'vitamin-b9_100g', 'vitamin-b12_100g', 'vitamin-c_100g', 'vitamin-d_100g', 'vitamin-e_100g', 'vitamin-k_100g'],
  64. 'products_minerals': ['code', 'calcium_100g', 'iron_100g', 'magnesium_100g', 'potassium_100g', 'zinc_100g']
  65. }
  66. # Schema Auto-Migration: check if columns mismatch, and drop table for clean recreation
  67. try:
  68. with engine.connect() as conn:
  69. for table_name, columns in groups.items():
  70. try:
  71. res = conn.execute(text(f"DESCRIBE {table_name}"))
  72. existing_cols = [row[0] for row in res.fetchall()]
  73. mismatch = False
  74. for col in columns:
  75. if col not in existing_cols:
  76. mismatch = True
  77. break
  78. if mismatch:
  79. print(f"⚠️ Columns mismatch for table {table_name}. Dropping table for recreation.")
  80. conn.execute(text(f"DROP TABLE IF EXISTS {table_name}"))
  81. conn.commit()
  82. except Exception:
  83. pass
  84. except Exception as e:
  85. print(f"Warning: Could not connect to database for schema check: {e}")
  86. # Pre-calculate what to read
  87. all_required_cols = list(set([col for cols in groups.values() for col in cols]))
  88. for chunk in pd.read_csv(filename, sep='\t', dtype=str, chunksize=chunk_size, on_bad_lines='skip', low_memory=False, encoding='utf-8'):
  89. chunks_count += 1
  90. if max_chunks > 0 and chunks_count > max_chunks:
  91. print(f"\nReached MAX_CHUNKS limit ({max_chunks}). Ingestion stopped early.")
  92. break
  93. try:
  94. # Drop rows with missing codes
  95. if 'code' not in chunk.columns:
  96. continue
  97. df = chunk.dropna(subset=['code']).drop_duplicates(subset=['code']).copy()
  98. # Clean and consolidate CSV data
  99. # 1. Clean code (must be numeric digits/characters, strip whitespace)
  100. df['code'] = df['code'].astype(str).str.strip()
  101. df = df[df['code'] != '']
  102. # 2. Clean product_name: strip whitespace, fill empty with generic name or brand, or skip if completely empty
  103. if 'product_name' in df.columns:
  104. df['product_name'] = df['product_name'].astype(str).str.strip()
  105. if 'generic_name' in df.columns:
  106. df['product_name'] = df['product_name'].fillna(df['generic_name'].astype(str).str.strip())
  107. if 'brands' in df.columns:
  108. df['product_name'] = df['product_name'].fillna(df['brands'].astype(str).str.strip())
  109. # Replace string representations of "nan" / "none"
  110. df['product_name'] = df['product_name'].replace(['nan', 'NaN', 'None', 'none', ''], None)
  111. # 3. Drop rows with missing or null product_name (consolidate only valid food items)
  112. df = df.dropna(subset=['product_name'])
  113. # 4. Clean URL columns: if not starts with http/https or contains 'invalid', set to None
  114. url_cols = [c for c in df.columns if 'url' in c.lower()]
  115. for col in url_cols:
  116. df[col] = df[col].astype(str).str.strip()
  117. df[col] = df[col].replace(['nan', 'NaN', 'None', 'none', ''], None)
  118. # Validate URL structure
  119. is_valid_url = df[col].str.startswith(('http://', 'https://'), na=False) & ~df[col].str.contains('invalid', case=False, na=False)
  120. df.loc[~is_valid_url, col] = None
  121. # Ensure all required columns exist in the chunk (fill with None if missing)
  122. for col in all_required_cols:
  123. if col not in df.columns:
  124. df[col] = None
  125. for table_name, columns in groups.items():
  126. slice_df = df[columns].copy()
  127. # Cast datatypes: core and allergens are TEXT, others are DOUBLE
  128. if table_name in ['products_core', 'products_allergens']:
  129. sql_dtypes = {col: LONGTEXT() for col in columns if col != 'code'}
  130. sql_dtypes['code'] = VARCHAR(255)
  131. else:
  132. # Convert to numeric (double) safely
  133. for col in columns:
  134. if col != 'code':
  135. slice_df[col] = pd.to_numeric(slice_df[col], errors='coerce')
  136. sql_dtypes = {col: DOUBLE() for col in columns if col != 'code'}
  137. sql_dtypes['code'] = VARCHAR(255)
  138. # Write to temp table
  139. temp_name = f"temp_{table_name}"
  140. slice_df.to_sql(temp_name, con=engine, if_exists='replace', index=False, dtype=sql_dtypes)
  141. # UPSERT into final table with Primary Key enforcement
  142. with engine.begin() as conn:
  143. # Ensure temp table has a primary key on code so LIKE copies it, or alter it later
  144. conn.execute(text(f"ALTER TABLE {temp_name} ADD PRIMARY KEY (code);"))
  145. conn.execute(text(f"CREATE TABLE IF NOT EXISTS {table_name} LIKE {temp_name}"))
  146. cols_str = ", ".join([f"`{c}`" for c in columns])
  147. # Generate ON DUPLICATE KEY UPDATE clause with COALESCE to fill nulls
  148. update_cols = ", ".join([f"`{c}` = COALESCE(`{table_name}`.`{c}`, VALUES(`{c}`))" for c in columns if c != 'code'])
  149. if update_cols:
  150. upsert_query = f"INSERT INTO {table_name} ({cols_str}) SELECT {cols_str} FROM {temp_name} ON DUPLICATE KEY UPDATE {update_cols}"
  151. else:
  152. upsert_query = f"INSERT IGNORE INTO {table_name} ({cols_str}) SELECT {cols_str} FROM {temp_name}"
  153. conn.execute(text(upsert_query))
  154. conn.execute(text(f"DROP TABLE IF EXISTS {temp_name}"))
  155. total_processed += len(df)
  156. print(f" Successfully appended {total_processed} rows into grouped tables...", end="\r")
  157. # Update rows loaded in database
  158. with engine.begin() as conn:
  159. conn.execute(text("""
  160. UPDATE ingestion_status
  161. SET rows_loaded = :rows
  162. WHERE id = :id
  163. """), {"rows": total_processed, "id": ingest_id})
  164. if total_processed % 50000 == 0:
  165. notifier.send_alert(f"Ingestion Milestone: {total_processed} rows processed")
  166. except BaseException as e:
  167. notifier.send_alert(f"Ingestion Exception: {str(e)}")
  168. print(f"\n [Warning] Chunk skipped due to error: {e}")
  169. notifier.send_alert(f"Ingestion Finished: {filename}")
  170. print(f"\n✅ Finished importing {filename}.")
  171. return True
  172. if __name__ == "__main__":
  173. print("Initiating OpenFoodFacts Grouped Vertical Ingestion Process...")
  174. engine = get_loader_engine()
  175. processed_en = ingest_file('data/en.openfoodfacts.org.products.csv', engine)
  176. processed_fr = ingest_file('data/fr.openfoodfacts.org.products.csv', engine)
  177. if not processed_en and not processed_fr:
  178. print("\n❌ Could not find CSVs.")
  179. else:
  180. print("\n🎉 Full database reload complete! Ready for AI RAG.")