Spaces:
Running
Running
Download archive_import.py from kugguk/electrocheap: direct link, hf CLI and curl.
- Browser
- Download file 19.9 kB
-
https://huggingface.co/spaces/kugguk/electrocheap/resolve/main/archive_import.py
- Command line
-
hf download hf://spaces/kugguk/electrocheap/archive_import.py
-
curl -L -o archive_import.py https://huggingface.co/spaces/kugguk/electrocheap/resolve/main/archive_import.py
19.9 kB
| """Bounded, in-memory bill imports. No raw PDFs, account IDs or text are retained.""" | |
| from collections import defaultdict | |
| from datetime import date, timedelta | |
| from io import BytesIO, StringIO | |
| from pathlib import PurePosixPath | |
| from zipfile import ZipFile, BadZipFile | |
| import calendar | |
| import csv | |
| import hashlib | |
| import hmac | |
| import json | |
| import math | |
| import re | |
| import secrets | |
| import stat | |
| import unicodedata | |
| from pypdf import PdfReader | |
| MAX_COMPRESSED = 25 * 1024 * 1024 | |
| MAX_EXPANDED = 100 * 1024 * 1024 | |
| MAX_MEMBER = 8 * 1024 * 1024 | |
| MAX_FILES = 250 | |
| MAX_PAGES = 30 | |
| PARSER_VERSION = "electrocheap-billing-import-v1" | |
| MONTHS = {"jan": 1, "fev": 2, "mar": 3, "abr": 4, "mai": 5, "jun": 6, | |
| "jul": 7, "ago": 8, "set": 9, "out": 10, "nov": 11, "dez": 12} | |
| DATE_RANGE = re.compile(r"(\d{1,2})\s+(?:de\s+)?([a-zç]+)(?:\s+(?:de\s+)?(\d{4}))?\s+a\s+(\d{1,2})\s+(?:de\s+)?([a-zç]+)(?:\s+(?:de\s+)?(\d{4}))?", re.I) | |
| AMOUNT = r"(?<![\d.,])(-?(?:\d{1,3}(?: \d{3})+|\d+)(?:,\d+)?)" | |
| def digest(data): | |
| return hashlib.sha256(data).hexdigest() | |
| def decimal(value): | |
| n = float(value.replace(" ", "").replace(".", "").replace(",", ".")) | |
| if not math.isfinite(n): | |
| raise ValueError("Nonfinite bill value.") | |
| return n | |
| def period(text, reference_year=None): | |
| match = DATE_RANGE.search(text.lower()) | |
| if not match: | |
| raise ValueError("Billing period could not be extracted.") | |
| d1, m1, y1, d2, m2, y2 = match.groups() | |
| m1, m2 = MONTHS[m1[:3]], MONTHS[m2[:3]] | |
| y2 = int(y2 or y1 or reference_year or date.today().year) | |
| y1 = int(y1 or (y2 - (m1 > m2))) | |
| start, end = date(y1, m1, int(d1)), date(y2, m2, int(d2)) | |
| if start > end or (end - start).days > 400: | |
| raise ValueError("Invalid or excessively long billing period.") | |
| return start, end | |
| def parse_edp(text, source_hash, key): | |
| header = re.search(r"Per[ií]odo de fatura[çc][ãa]o:\s*([^\n]+)", text, re.I) | |
| if not header: | |
| raise ValueError("EDP billing period missing.") | |
| start, end = period(header.group(1)) | |
| cpe = re.search(r"\bPT\s*\d[\d ]{14,24}[A-Z]{2}\b", text) | |
| if not cpe: | |
| raise ValueError("Cannot safely separate electricity meters: CPE not found.") | |
| meter_id = hmac.new(key, cpe.group().replace(" ", "").encode(), "sha256").hexdigest()[:16] | |
| # Invoice identifiers are used only for duplicate detection, never returned. | |
| invoice_re = re.compile(r"Fatura\s+n[ºo.°]+\s*(FT[^\n]+?)\s*De:\s*[^\n]+?Valor:\s*" + AMOUNT + r"\s*€", re.I) | |
| invoices = list(invoice_re.finditer(text)) | |
| if not invoices: | |
| raise ValueError("EDP invoice charge could not be extracted.") | |
| first = invoices[0] | |
| invoice_key = digest(re.sub(r"\s+", "", first.group(1)).encode()) | |
| electricity_total = decimal(first.group(2)) | |
| unique = set() | |
| extra_electricity = 0.0 | |
| excluded_services = 0.0 | |
| for i, match in enumerate(invoices): | |
| ident = re.sub(r"\s+", "", match.group(1)) | |
| if ident in unique: | |
| continue | |
| unique.add(ident) | |
| if ident == re.sub(r"\s+", "", first.group(1)): | |
| continue | |
| section = text[match.end():invoices[i+1].start() if i+1 < len(invoices) else len(text)] | |
| value = decimal(match.group(2)) | |
| if re.search(r"Contribui[çc][ãa]o\s+Audiovisual", section, re.I): | |
| extra_electricity += value | |
| else: | |
| excluded_services += value | |
| energy_section = text[first.end():] | |
| power = re.search(r"Pot[eê]ncia\s*\(" + AMOUNT + r"\s*kVA\)", energy_section, re.I) | |
| if not power: | |
| raise ValueError("EDP contracted power missing; manual review required.") | |
| energy_only = energy_section[:power.start()] | |
| consumption, rates = 0.0, [] | |
| estimated = False | |
| for line in energy_only.splitlines(): | |
| if "estimado" in line.lower(): | |
| estimated = True | |
| found = re.search(AMOUNT + r"\s*kWh\s+" + AMOUNT + r"\s*€\s+" + AMOUNT + r"\s*€", line) | |
| if found and not re.search(r"IEC|imposto|taxa", line, re.I): | |
| kwh, rate = decimal(found.group(1)), decimal(found.group(2)) | |
| gross = decimal(found.group(3)) | |
| if not math.isclose(kwh*rate,gross,abs_tol=.03,rel_tol=.001): | |
| raise ValueError("EDP quantity/unit-price/charge reconciliation failed.") | |
| if kwh < 0 or not 0 <= rate <= 10: | |
| raise ValueError("EDP consumption adjustments need manual review.") | |
| consumption += kwh | |
| dates = DATE_RANGE.search(line) | |
| rs, re_ = period(dates.group(), end.year) if dates else (start, end) | |
| discount = re.search(r"(\d+(?:,\d+)?)\s*%\s*\(", line) | |
| fraction = decimal(discount.group(1)) / 100 if discount else 0 | |
| rates.append({"period_start": rs.isoformat(), "period_end": re_.isoformat(), | |
| "quantity_kwh": kwh, | |
| "rate_per_kwh": round(rate * (1 - fraction), 6), | |
| "list_rate_per_kwh": rate, "tax_included": False, | |
| "date_basis": "line_period" if dates else "invoice_period; rate-change date uncertain"}) | |
| if not rates: | |
| raise ValueError("No supported EDP energy charge rows found.") | |
| daily_rates = [] | |
| power_section = energy_section[power.end():] | |
| for line in power_section.splitlines(): | |
| if "Tarifa" in line or "tarifa" in line: | |
| continue | |
| found = re.search(r"(\d+)\s*dias\s+" + AMOUNT + r"\s*€", line) | |
| if found: | |
| dates = DATE_RANGE.search(line) | |
| ds, de = period(dates.group(), end.year) if dates else (start, end) | |
| discount = re.search(r"(\d+(?:,\d+)?)\s*%\s*\(", line) | |
| fraction = decimal(discount.group(1)) / 100 if discount else 0 | |
| daily_rates.append({"period_start": ds.isoformat(), "period_end": de.isoformat(), | |
| "daily_charge": round(decimal(found.group(2)) * (1 - fraction), 6), | |
| "tax_included": False}) | |
| if re.search(r"A Total|Total.*sem IVA", line): | |
| break | |
| return {"profile_id": "meter-" + meter_id, "country": "PT", "region": "PT-mainland", | |
| "currency": "EUR", "provider": "EDP Comercial", "tariff_type": "flat", | |
| "contracted_power_kva": decimal(power.group(1)), "meter_type": "standard", | |
| "period_start": start.isoformat(), "period_end": end.isoformat(), | |
| "kwh": consumption, "electricity_charges": round(electricity_total + extra_electricity, 2), | |
| "excluded_service_charges": round(excluded_services, 2), | |
| "estimated_readings_present": estimated, "energy_rates": rates, "daily_rates": daily_rates, | |
| "source_sha256": source_hash, "_invoice_key": invoice_key, | |
| "cost_basis": "Electricity invoice plus separately invoiced audiovisual charge; excludes services, credit notes and payment adjustments.", | |
| "review_required": True} | |
| def parse_pdf(content, key): | |
| reader = PdfReader(BytesIO(content), strict=False) | |
| if reader.is_encrypted or len(reader.pages) > MAX_PAGES: | |
| raise ValueError("Encrypted PDFs or PDFs over 30 pages are unsupported.") | |
| text = "\n".join(p.extract_text() or "" for p in reader.pages) | |
| if len(text) > 500_000: | |
| raise ValueError("PDF text limit exceeded.") | |
| if len(text.strip()) < 60: | |
| return None, "scanned_pdf_requires_ocr_or_normalized_csv" | |
| text = unicodedata.normalize("NFKC", text) | |
| if "EDP Comercial" in text: | |
| return parse_edp(text, digest(content), key), None | |
| if re.search(r"água|saneamento|res[ií]duos.*urbanos", text, re.I): | |
| return None, "water_bill_excluded_from_electricity" | |
| return None, "unsupported_pdf_template; supply normalized CSV/JSON" | |
| def unpack_inputs(files): | |
| members, expanded = [], 0 | |
| if not 1 <= len(files) <= 10 or sum(len(b) for _, b in files) > MAX_COMPRESSED: | |
| raise ValueError("Supply 1–10 files, at most 25 MiB combined.") | |
| for filename, content in files: | |
| extension = PurePosixPath(filename.lower()).suffix | |
| if extension == ".zip": | |
| try: | |
| with ZipFile(BytesIO(content)) as archive: | |
| infos = archive.infolist() | |
| if len(infos) > MAX_FILES: | |
| raise ValueError("ZIP contains more than 250 members.") | |
| for info in infos: | |
| path = PurePosixPath(info.filename.replace("\\", "/")) | |
| mode = info.external_attr >> 16 | |
| if path.is_absolute() or ".." in path.parts or re.match(r"^[a-zA-Z]:", str(path)) or stat.S_ISLNK(mode) or info.flag_bits & 1: | |
| raise ValueError("Unsafe ZIP path, symlink or encrypted member.") | |
| if info.is_dir() or path.name.startswith(".") or "__MACOSX" in path.parts: | |
| continue | |
| expanded += info.file_size | |
| if info.file_size > MAX_MEMBER or expanded > MAX_EXPANDED or info.file_size > max(info.compress_size, 1) * 200: | |
| raise ValueError("ZIP expansion/file/ratio limit exceeded.") | |
| if path.suffix.lower() == ".zip": | |
| raise ValueError("Nested ZIP archives are unsupported.") | |
| members.append((str(path), archive.read(info))) | |
| except BadZipFile: | |
| raise ValueError("Invalid ZIP archive.") from None | |
| else: | |
| expanded += len(content) | |
| if len(content) > MAX_MEMBER: | |
| raise ValueError("Individual file exceeds 8 MiB.") | |
| members.append((filename, content)) | |
| if len(members) > MAX_FILES or expanded > MAX_EXPANDED: | |
| raise ValueError("Import exceeds 250 files / 100 MiB expanded.") | |
| return members | |
| def monthly_from_invoices(invoices): | |
| buckets = defaultdict(lambda: {"kwh": 0.0, "billed_total": 0.0, "days": set(), "sources": set()}) | |
| overlaps = set() | |
| for bill in invoices: | |
| start, end = date.fromisoformat(bill["period_start"]), date.fromisoformat(bill["period_end"]) | |
| days = (end - start).days + 1 | |
| for offset in range(days): | |
| current = start + timedelta(days=offset) | |
| month = current.strftime("%Y-%m") | |
| bucket = buckets[month] | |
| if current in bucket["days"]: | |
| overlaps.add(month) | |
| bucket["days"].add(current) | |
| bucket["sources"].add(bill["source_sha256"]) | |
| bucket["kwh"] += bill["kwh"] / days | |
| bucket["billed_total"] += bill["electricity_charges"] / days | |
| rows = [] | |
| for month, bucket in sorted(buckets.items()): | |
| y, m = map(int, month.split("-")) | |
| rows.append({"month": month, "kwh": round(bucket["kwh"], 6), | |
| "billed_total": round(bucket["billed_total"], 6), "currency": invoices[0]["currency"], | |
| "coverage": round(len(bucket["days"]) / calendar.monthrange(y, m)[1], 6), | |
| "allocation": "uniform daily allocation within each invoice; not measured monthly usage", | |
| "overlap": month in overlaps, "source_sha256": sorted(bucket["sources"])}) | |
| return rows | |
| def import_files(files, key=None): | |
| key = key or secrets.token_bytes(32) | |
| members = unpack_inputs(files) | |
| invoices, documents, normalized, seen_bytes, seen_invoice = [], [], [], set(), set() | |
| for index, (filename, content) in enumerate(members): | |
| source_hash = digest(content) | |
| doc = {"document_id": f"document-{index+1:04d}", "sha256": source_hash, "bytes": len(content)} | |
| if source_hash in seen_bytes: | |
| doc["status"] = "duplicate_file_excluded" | |
| documents.append(doc) | |
| continue | |
| seen_bytes.add(source_hash) | |
| extension = PurePosixPath(filename.lower()).suffix | |
| try: | |
| if extension == ".pdf": | |
| bill, excluded = parse_pdf(content, key) | |
| if bill: | |
| if bill["_invoice_key"] in seen_invoice: | |
| doc["status"] = "duplicate_invoice_excluded" | |
| else: | |
| seen_invoice.add(bill.pop("_invoice_key")) | |
| bill["document_id"] = doc["document_id"] | |
| invoices.append(bill) | |
| doc["status"] = "electricity_extracted_review_required" | |
| else: | |
| doc["status"] = excluded | |
| elif extension in {".csv", ".json"}: | |
| text = content.decode("utf-8-sig") | |
| rows = list(csv.DictReader(StringIO(text))) if extension == ".csv" else json.loads(text) | |
| if not isinstance(rows, list) or len(rows) > 5000: | |
| raise ValueError("Normalized bill files need a list of at most 5000 rows.") | |
| allowed = {"profile_id", "country", "region", "provider", "meter_type", "month", "kwh", "billed_total", "currency", "peak_kwh"} | |
| staged=[] | |
| for row in rows: | |
| if not isinstance(row, dict) or set(row) - allowed or not {"month", "kwh", "billed_total", "currency"} <= set(row): | |
| raise ValueError("Normalized bills contain missing or unsupported fields; remove personal identifiers.") | |
| if not re.fullmatch(r"\d{4}-(0[1-9]|1[0-2])", str(row["month"])): | |
| raise ValueError("Use YYYY-MM months.") | |
| country = row.get("country", "AU" if row["currency"] == "AUD" else "PT") | |
| if country not in {"PT", "DE", "AU"} or row["currency"] != ("AUD" if country == "AU" else "EUR"): | |
| raise ValueError("Country/currency mismatch.") | |
| safe = {k: row[k] for k in allowed & row.keys()} | |
| original_id = str(row.get("profile_id", "uploaded-profile")) | |
| safe["profile_id"] = "profile-" + hmac.new(key, original_id.encode(), "sha256").hexdigest()[:16] | |
| safe["country"] = country | |
| for field in ["kwh", "billed_total", "peak_kwh"]: | |
| if field in safe: | |
| value = float(safe[field]) | |
| if not math.isfinite(value) or not 0 <= value <= 1e8: | |
| raise ValueError("Bill values must be finite and nonnegative.") | |
| safe[field] = value | |
| safe.update(coverage=1.0, allocation="user-supplied monthly totals", source_sha256=[source_hash]) | |
| staged.append(safe) | |
| normalized.extend(staged) | |
| doc["status"] = "normalized_monthly_rows_imported" | |
| else: | |
| doc["status"] = "unsupported_file_type_excluded" | |
| except Exception as error: | |
| # PDF text, paths and upstream parser exceptions may contain private data. | |
| doc["status"] = "manual_review_required" | |
| doc["reason"] = str(error) if isinstance(error, ValueError) and extension != ".pdf" else "Template or PDF parsing failed; no financial values inferred." | |
| documents.append(doc) | |
| grouped = defaultdict(list) | |
| for bill in invoices: | |
| grouped[bill["profile_id"]].append(bill) | |
| profiles, price_history = [], [] | |
| for pid, bills in sorted(grouped.items()): | |
| monthly = monthly_from_invoices(bills) | |
| first = bills[0] | |
| covered = sum(row["coverage"] * calendar.monthrange(*map(int, row["month"].split("-")))[1] for row in monthly) | |
| total_kwh = sum(b["kwh"] for b in bills) | |
| total_cost = sum(b["electricity_charges"] for b in bills) | |
| overlap = any(row["overlap"] for row in monthly) | |
| profiles.append({"profile_id": pid, "country": first["country"], "region": first["region"], | |
| "currency": first["currency"], "provider": first["provider"], | |
| "meter_type": first["meter_type"], "contracted_power_kva": first["contracted_power_kva"], | |
| "invoice_count": len(bills), "observed_kwh": round(total_kwh, 3), | |
| "observed_electricity_charges": round(total_cost, 2), "covered_days": round(covered), | |
| "annual_kwh": round(total_kwh * 365 / covered, 3) if covered and not overlap else None, | |
| "current_annual_bill": round(total_cost * 365 / covered, 2) if covered and not overlap else None, | |
| "profile_source": "observed invoice totals annualized over covered days", | |
| "needs_review": True, "overlapping_periods": overlap, "monthly": monthly, | |
| "period_start": min(b["period_start"] for b in bills), "period_end": max(b["period_end"] for b in bills)}) | |
| for bill in bills: | |
| for rate in bill["energy_rates"]: | |
| price_history.append({**rate, "provider": first["provider"], "profile_id": pid, | |
| "tariff_id": pid, "country": first["country"], "currency": first["currency"], | |
| "unit": "EUR/kWh", "observed_at": bill["period_end"], | |
| "source_sha256": bill["source_sha256"]}) | |
| for pid in sorted({r["profile_id"] for r in normalized}): | |
| rows = sorted([r for r in normalized if r["profile_id"] == pid], key=lambda x: x["month"]) | |
| if len({r["month"] for r in rows}) != len(rows): | |
| raise ValueError("Duplicate normalized profile months; merge deliberately before import.") | |
| currencies = {r["currency"] for r in rows} | |
| if len(currencies) != 1 or len({r["country"] for r in rows}) != 1: | |
| raise ValueError("A profile cannot mix countries or currencies.") | |
| annual = rows[-12:] | |
| complete_year = len(annual) == 12 and all((int(b["month"][:4])*12+int(b["month"][5:]))-(int(a["month"][:4])*12+int(a["month"][5:])) == 1 for a,b in zip(annual,annual[1:])) | |
| profiles.append({"profile_id": pid, "country": rows[0]["country"], "region": rows[0].get("region", "PT-mainland" if rows[0]["country"]=="PT" else ""), | |
| "currency": rows[0]["currency"], "meter_type": rows[0].get("meter_type", "standard"), | |
| "provider": rows[0].get("provider", "supplied profile"), "monthly": rows, | |
| "annual_kwh": sum(r["kwh"] for r in annual) if complete_year else None, | |
| "current_annual_bill": sum(r["billed_total"] for r in annual) if complete_year else None, | |
| "profile_source": "latest supplied 12 complete months" if complete_year else "incomplete supplied monthly history", | |
| "needs_review": not complete_year}) | |
| return {"status": "billing_imported", "parser_version": PARSER_VERSION, | |
| "archive_sha256": [digest(b) for _, b in files], "documents": documents, | |
| "electricity_invoice_count": len(invoices), "profiles": profiles, | |
| "invoices": invoices, "price_history": price_history, | |
| "privacy": "In-memory extraction. Raw documents, names, addresses, CPEs, account and invoice IDs are not retained or returned. Anonymous normalized results expire after one hour.", | |
| "limits": ["EDP Portugal text PDFs plus normalized PT/DE/AU monthly CSV/JSON are supported; other PDF templates and scans need manual normalization.", | |
| "PDF months are allocated uniformly over invoice days, not measured monthly consumption. Review totals before comparison.", | |
| "Water, services and payment adjustments are excluded; bundled discounts and credit notes require manual review.", | |
| "Observed provider unit prices exclude VAT and cannot be substituted directly for tax-inclusive offers."]} | |