ingest_csv.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. import pandas as pd
  2. import myloginpath
  3. import urllib.parse
  4. from sqlalchemy import create_engine, text
  5. import os
  6. import sys
  7. def get_loader_engine():
  8. try:
  9. conf = myloginpath.parse('app_loader')
  10. user = conf.get('user')
  11. password = urllib.parse.quote_plus(conf.get('password'))
  12. host = conf.get('host', '127.0.0.1')
  13. database = 'food_db'
  14. # Build strict SQLAlchemy PyMySQL string
  15. conn_str = f"mysql+pymysql://{user}:{password}@{host}/{database}?charset=utf8mb4"
  16. return create_engine(conn_str)
  17. except Exception as e:
  18. print(f"❌ Failed to parse myloginpath or create engine: {e}")
  19. sys.exit(1)
  20. def ingest_file(filename, engine):
  21. if not os.path.exists(filename):
  22. print(f"File {filename} not found locally.")
  23. return False
  24. print(f"\n🚀 Found {filename}! Starting extreme batch ingestion...")
  25. chunk_size = 5000
  26. total_processed = 0
  27. # Read dynamically without filtering. Setting low_memory=False to let pandas parse column types flexibly
  28. # Forced utf-8 encoding to prevent French accent corruption on Windows OS defaults
  29. for chunk in pd.read_csv(filename, sep='\t', dtype=str, chunksize=chunk_size, on_bad_lines='skip', low_memory=False, encoding='utf-8'):
  30. try:
  31. # Drop duplicates by code natively
  32. if 'code' in chunk.columns:
  33. df = chunk.drop_duplicates(subset=['code'])
  34. else:
  35. # Only keep the minimum columns required by our clinical analytical schema!
  36. target_cols = [
  37. 'code', 'product_name', 'generic_name', 'brands', 'allergens', 'ingredients_text',
  38. 'proteins_100g', 'fat_100g', 'carbohydrates_100g', 'sugars_100g', 'sodium_100g', 'energy-kcal_100g',
  39. 'vitamin-c_100g', 'iron_100g', 'calcium_100g'
  40. ]
  41. # Use intersection in case some CSV chunks lack certain columns
  42. exist_cols = [c for c in target_cols if c in df.columns]
  43. df = df[exist_cols]
  44. df.to_sql('products', con=engine, if_exists='append', index=False)
  45. total_processed += len(df)
  46. print(f" Successfully appended {total_processed} rows (Dynamic schema)...", end="\r")
  47. except BaseException as e:
  48. if "Duplicate entry" in str(e):
  49. pass
  50. else:
  51. print(f"\n [Warning] Chunk skipped due to internal structural error: {e}")
  52. print(f"\n✅ Finished importing {filename}.")
  53. return True
  54. def create_indexes(engine):
  55. print("\n🛠️ Creating performance indexes on newly generated table...")
  56. # B-TREE and FULLTEXT INDEXES created post-ingestion for extreme speed
  57. try:
  58. with engine.begin() as connection:
  59. print(" Building Primary Key on `code`...")
  60. connection.execute(text("ALTER TABLE products MODIFY code VARCHAR(50);"))
  61. connection.execute(text("ALTER TABLE products ADD PRIMARY KEY (code);"))
  62. print(" Building Fulltext Indexes...")
  63. connection.execute(text("CREATE FULLTEXT INDEX ft_idx_search ON products(product_name, ingredients_text, brands);"))
  64. print(" Building B-TREE Indexes on core macros...")
  65. macro_cols = ['energy-kcal_100g', 'fat_100g', 'carbohydrates_100g', 'proteins_100g', 'sugars_100g', 'sodium_100g', 'iron_100g', 'calcium_100g', 'vitamin-c_100g']
  66. for col in macro_cols:
  67. try:
  68. connection.execute(text(f"ALTER TABLE products MODIFY `{col}` DOUBLE;"))
  69. connection.execute(text(f"CREATE INDEX idx_{col.replace('-', '_')} ON products(`{col}`);"))
  70. except:
  71. pass
  72. print("✅ Indexing Complete!")
  73. except Exception as e:
  74. print(f"❌ Indexing encountered an issue: {e}")
  75. if __name__ == "__main__":
  76. print("Initiating OpenFoodFacts CSV Ingestion Process...")
  77. engine = get_loader_engine()
  78. processed_en = ingest_file('en.openfoodfacts.org.products.csv', engine)
  79. processed_fr = ingest_file('fr.openfoodfacts.org.products.csv', engine)
  80. if not processed_en and not processed_fr:
  81. print("\n❌ Could not find either 'en.openfoodfacts.org.products.csv' or 'fr.openfoodfacts.org.products.csv'.")
  82. print("Please download them directly into the root folder and run this script again.")
  83. else:
  84. # Build indexes now that all data is appended!
  85. create_indexes(engine)
  86. print("\n🎉 Full database reload and indexing complete! Ready for AI RAG.")