ingest_csv.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. #!/usr/bin/env python3
  2. #ident "@(#)$Format:LocalFoodAI:app.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 ingest_file(filename, engine):
  33. if not os.path.exists(filename):
  34. print(f"File {filename} not found locally.")
  35. return False
  36. print(f"\n🚀 Found {filename}! Starting grouped vertical partition ingestion...")
  37. chunk_size = 10000
  38. total_processed = 0
  39. max_chunks = int(os.environ.get('MAX_CHUNKS', '0'))
  40. chunks_count = 0
  41. # Define the groupings
  42. groups = {
  43. 'products_core': [
  44. 'code', 'product_name', 'generic_name', 'brands', 'ingredients_text',
  45. 'url', 'image_url', 'image_small_url', 'image_ingredients_url',
  46. 'image_ingredients_small_url', 'image_nutrition_url', 'image_nutrition_small_url'
  47. ],
  48. 'products_allergens': ['code', 'allergens'],
  49. 'products_macros': ['code', 'energy-kcal_100g', 'proteins_100g', 'fat_100g', 'carbohydrates_100g', 'sugars_100g', 'fiber_100g', 'sodium_100g', 'salt_100g', 'cholesterol_100g'],
  50. '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'],
  51. 'products_minerals': ['code', 'calcium_100g', 'iron_100g', 'magnesium_100g', 'potassium_100g', 'zinc_100g']
  52. }
  53. # Schema Auto-Migration: check if columns mismatch, and drop table for clean recreation
  54. try:
  55. with engine.connect() as conn:
  56. for table_name, columns in groups.items():
  57. try:
  58. res = conn.execute(text(f"DESCRIBE {table_name}"))
  59. existing_cols = [row[0] for row in res.fetchall()]
  60. mismatch = False
  61. for col in columns:
  62. if col not in existing_cols:
  63. mismatch = True
  64. break
  65. if mismatch:
  66. print(f"⚠️ Columns mismatch for table {table_name}. Dropping table for recreation.")
  67. conn.execute(text(f"DROP TABLE IF EXISTS {table_name}"))
  68. conn.commit()
  69. except Exception:
  70. pass
  71. except Exception as e:
  72. print(f"Warning: Could not connect to database for schema check: {e}")
  73. # Pre-calculate what to read
  74. all_required_cols = list(set([col for cols in groups.values() for col in cols]))
  75. for chunk in pd.read_csv(filename, sep='\t', dtype=str, chunksize=chunk_size, on_bad_lines='skip', low_memory=False, encoding='utf-8'):
  76. chunks_count += 1
  77. if max_chunks > 0 and chunks_count > max_chunks:
  78. print(f"\nReached MAX_CHUNKS limit ({max_chunks}). Ingestion stopped early.")
  79. break
  80. try:
  81. # Drop rows with missing codes
  82. if 'code' not in chunk.columns:
  83. continue
  84. df = chunk.dropna(subset=['code']).drop_duplicates(subset=['code']).copy()
  85. # Clean and consolidate CSV data
  86. # 1. Clean code (must be numeric digits/characters, strip whitespace)
  87. df['code'] = df['code'].astype(str).str.strip()
  88. df = df[df['code'] != '']
  89. # 2. Clean product_name: strip whitespace, fill empty with generic name or brand, or skip if completely empty
  90. if 'product_name' in df.columns:
  91. df['product_name'] = df['product_name'].astype(str).str.strip()
  92. if 'generic_name' in df.columns:
  93. df['product_name'] = df['product_name'].fillna(df['generic_name'].astype(str).str.strip())
  94. if 'brands' in df.columns:
  95. df['product_name'] = df['product_name'].fillna(df['brands'].astype(str).str.strip())
  96. # Replace string representations of "nan" / "none"
  97. df['product_name'] = df['product_name'].replace(['nan', 'NaN', 'None', 'none', ''], None)
  98. # 3. Drop rows with missing or null product_name (consolidate only valid food items)
  99. df = df.dropna(subset=['product_name'])
  100. # 4. Clean URL columns: if not starts with http/https or contains 'invalid', set to None
  101. url_cols = [c for c in df.columns if 'url' in c.lower()]
  102. for col in url_cols:
  103. df[col] = df[col].astype(str).str.strip()
  104. df[col] = df[col].replace(['nan', 'NaN', 'None', 'none', ''], None)
  105. # Validate URL structure
  106. is_valid_url = df[col].str.startswith(('http://', 'https://'), na=False) & ~df[col].str.contains('invalid', case=False, na=False)
  107. df.loc[~is_valid_url, col] = None
  108. # Ensure all required columns exist in the chunk (fill with None if missing)
  109. for col in all_required_cols:
  110. if col not in df.columns:
  111. df[col] = None
  112. for table_name, columns in groups.items():
  113. slice_df = df[columns].copy()
  114. # Cast datatypes: core and allergens are TEXT, others are DOUBLE
  115. if table_name in ['products_core', 'products_allergens']:
  116. sql_dtypes = {col: LONGTEXT() for col in columns if col != 'code'}
  117. sql_dtypes['code'] = VARCHAR(255)
  118. else:
  119. # Convert to numeric (double) safely
  120. for col in columns:
  121. if col != 'code':
  122. slice_df[col] = pd.to_numeric(slice_df[col], errors='coerce')
  123. sql_dtypes = {col: DOUBLE() for col in columns if col != 'code'}
  124. sql_dtypes['code'] = VARCHAR(255)
  125. # Write to temp table
  126. temp_name = f"temp_{table_name}"
  127. slice_df.to_sql(temp_name, con=engine, if_exists='replace', index=False, dtype=sql_dtypes)
  128. # UPSERT into final table with Primary Key enforcement
  129. with engine.begin() as conn:
  130. # Ensure temp table has a primary key on code so LIKE copies it, or alter it later
  131. conn.execute(text(f"ALTER TABLE {temp_name} ADD PRIMARY KEY (code);"))
  132. conn.execute(text(f"CREATE TABLE IF NOT EXISTS {table_name} LIKE {temp_name}"))
  133. cols_str = ", ".join([f"`{c}`" for c in columns])
  134. # Generate ON DUPLICATE KEY UPDATE clause with COALESCE to fill nulls
  135. update_cols = ", ".join([f"`{c}` = COALESCE(`{table_name}`.`{c}`, VALUES(`{c}`))" for c in columns if c != 'code'])
  136. if update_cols:
  137. upsert_query = f"INSERT INTO {table_name} ({cols_str}) SELECT {cols_str} FROM {temp_name} ON DUPLICATE KEY UPDATE {update_cols}"
  138. else:
  139. upsert_query = f"INSERT IGNORE INTO {table_name} ({cols_str}) SELECT {cols_str} FROM {temp_name}"
  140. conn.execute(text(upsert_query))
  141. conn.execute(text(f"DROP TABLE IF EXISTS {temp_name}"))
  142. total_processed += len(df)
  143. print(f" Successfully appended {total_processed} rows into grouped tables...", end="\r")
  144. if total_processed % 50000 == 0:
  145. notifier.send_alert(f"Ingestion Milestone: {total_processed} rows processed")
  146. except BaseException as e:
  147. notifier.send_alert(f"Ingestion Exception: {str(e)}")
  148. print(f"\n [Warning] Chunk skipped due to error: {e}")
  149. notifier.send_alert(f"Ingestion Finished: {filename}")
  150. print(f"\n✅ Finished importing {filename}.")
  151. return True
  152. if __name__ == "__main__":
  153. print("Initiating OpenFoodFacts Grouped Vertical Ingestion Process...")
  154. engine = get_loader_engine()
  155. processed_en = ingest_file('data/en.openfoodfacts.org.products.csv', engine)
  156. processed_fr = ingest_file('data/fr.openfoodfacts.org.products.csv', engine)
  157. if not processed_en and not processed_fr:
  158. print("\n❌ Could not find CSVs.")
  159. else:
  160. print("\n🎉 Full database reload complete! Ready for AI RAG.")