"""Refresh the local Open Food Facts products (Canada + United States) from their nightly file. Run weekly by refresh-products.ps1 (Task Scheduler). Usage: python -m scripts.import_off [--force] [--file path.csv.gz] The owner URL is the table owner's, like the migrations. OFF_CONTACT_EMAIL (setting, never in code) goes in the User-Agent. The download goes to a temporary file that is continued if it is cut off, then read row by row. Old data is replaced only after a clean, sane read. No product data is printed. """ import argparse import hashlib import sys import tempfile from pathlib import Path import psycopg from app import offimport from app.adapters.off import contact def main() -> int: ap = argparse.ArgumentParser() ap.add_argument("owner_url") ap.add_argument( "--force", action="store_true", help="import even if the file is unchanged" ) ap.add_argument( "--file", type=Path, help="read this local .csv.gz instead of downloading" ) ap.add_argument( "--workdir", type=Path, default=Path(tempfile.gettempdir()) / "meal-site-off" ) args = ap.parse_args() who = contact() if args.file is None and who is None: print("OFF_CONTACT_EMAIL is not set; not downloading.") return 2 opener = offimport.make_opener() with psycopg.connect(args.owner_url, autocommit=True) as conn: if args.file is not None: path, src = ( args.file, offimport.Source( f"file:{args.file.stat().st_mtime}", args.file.stat().st_size ), ) else: assert who is not None try: src = offimport.head(opener, who) except (OSError, ValueError) as e: note = f"{type(e).__name__}: could not reach Open Food Facts" conn.execute( "insert into off_imports (status, note, finished_at) values ('failed', %s, clock_timestamp())", (note,), ) print(note) return 1 if not args.force and offimport.unchanged(conn, src): conn.execute( "insert into off_imports (status, note, finished_at, source_last_modified, source_bytes) values ('unchanged', 'same file as the last import', clock_timestamp(), %s, %s)", (src.last_modified, src.size), ) print("The file has not changed since the last import; nothing to do.") return 0 args.workdir.mkdir(parents=True, exist_ok=True) # the part file's name holds the file's version, so a new version never continues an # old part; parts of other versions are deleted tag = hashlib.sha256( f"{src.last_modified}|{src.size}".encode() ).hexdigest()[:12] for old in args.workdir.glob("off*.gz.part"): if old.name != f"off-{tag}.gz.part": old.unlink(missing_ok=True) path = args.workdir / f"off-{tag}.gz.part" print( f"Downloading {src.size or '?'} bytes (it continues if interrupted)..." ) try: offimport.download(opener, who, path, src.size) except (OSError, ValueError) as e: note = f"{type(e).__name__}: the download did not finish; it continues next time" conn.execute( "insert into off_imports (status, note, finished_at) values ('failed', %s, clock_timestamp())", (note,), ) print(note) return 1 status, note = offimport.import_file(args.owner_url, path, src) print(f"{status}: {note}") if args.file is None and "(rule:" not in note: # done, refused or failed: a failed or refused one starts fresh. A table-rule failure keeps # the file (the download was fine), so a fixed importer can run on it without 2 more hours. path.unlink(missing_ok=True) return 0 if status == "ok" else 1 if __name__ == "__main__": sys.exit(main())