1
0

ingest_csv.py 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  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. df = chunk
  36. # Eliminate completely empty columns to save storage
  37. df.dropna(axis=1, how='all', inplace=True)
  38. # Segment the dataframe into chunks of 50 columns each to bypass InnoDB constraints
  39. cols = list(df.columns)
  40. if 'code' in cols: cols.remove('code')
  41. p_chunk_size = 4 # Extreme safe size for TEXT columns to stay under 8126 byte row limit
  42. chunks = [cols[i:i + p_chunk_size] for i in range(0, len(cols), p_chunk_size)]
  43. for i, col_chunk in enumerate(chunks):
  44. table_name = f'products_{i+1}'
  45. df_slice = df[['code'] + col_chunk].copy()
  46. df_slice.to_sql(table_name, con=engine, if_exists='append', index=False)
  47. total_processed += len(df)
  48. print(f" Successfully appended {total_processed} rows (Dynamic schema)...", end="\r")
  49. except BaseException as e:
  50. if "Duplicate entry" in str(e):
  51. pass
  52. else:
  53. print(f"\n [Warning] Chunk skipped due to error: {e}")
  54. print(f"\n✅ Finished importing {filename}.")
  55. return True
  56. def create_indexes(engine):
  57. # Determine how many tables were actually created
  58. num_tables = 0
  59. with engine.connect() as conn:
  60. res = conn.execute(text("SHOW TABLES LIKE 'products_%'"))
  61. num_tables = len(res.fetchall())
  62. print(f"\n🛠️ Creating performance indexes on {num_tables} partition tables...")
  63. try:
  64. with engine.begin() as connection:
  65. # Enforce Primary Keys on ALL partitions
  66. for i in range(1, num_tables + 1):
  67. try:
  68. connection.execute(text(f"ALTER TABLE products_{i} MODIFY code VARCHAR(50);"))
  69. connection.execute(text(f"ALTER TABLE products_{i} ADD PRIMARY KEY (code);"))
  70. except: pass
  71. print(" Building Global MySQL VIEW...")
  72. view_sql = f"CREATE VIEW products AS SELECT p1.* "
  73. joins = []
  74. for i in range(2, num_tables + 1):
  75. # Get columns for this table except 'code'
  76. cols_res = connection.execute(text(f"SHOW COLUMNS FROM products_{i}"))
  77. table_cols = [c[0] for c in cols_res.fetchall() if c[0] != 'code']
  78. if table_cols:
  79. view_sql += ", " + ", ".join([f"p{i}.`{c}`" for c in table_cols])
  80. joins.append(f"LEFT JOIN products_{i} p{i} ON p1.code = p{i}.code")
  81. view_sql += " FROM products_1 p1 " + " ".join(joins)
  82. try:
  83. connection.execute(text(view_sql))
  84. except Exception as ev:
  85. print(f" Warning: View creation failed: {ev}")
  86. print("✅ Indexing Complete!")
  87. except Exception as e:
  88. print(f"❌ Indexing encountered an issue: {e}")
  89. if __name__ == "__main__":
  90. print("Initiating OpenFoodFacts CSV Ingestion Process...")
  91. engine = get_loader_engine()
  92. processed_en = ingest_file('en.openfoodfacts.org.products.csv', engine)
  93. processed_fr = ingest_file('fr.openfoodfacts.org.products.csv', engine)
  94. if not processed_en and not processed_fr:
  95. print("\n❌ Could not find either 'en.openfoodfacts.org.products.csv' or 'fr.openfoodfacts.org.products.csv'.")
  96. print("Please download them directly into the root folder and run this script again.")
  97. else:
  98. # Build indexes now that all data is appended!
  99. create_indexes(engine)
  100. print("\n🎉 Full database reload and indexing complete! Ready for AI RAG.")