Spaces:
Sleeping
Sleeping
Download backend/core/loader.py from bevisssssss/AI: direct link, hf CLI and curl.
- Browser
- Download file 8.63 kB
-
https://huggingface.co/spaces/bevisssssss/AI/resolve/main/backend/core/loader.py
- Command line
-
hf download hf://spaces/bevisssssss/AI/backend/core/loader.py
-
curl -L -o loader.py https://huggingface.co/spaces/bevisssssss/AI/resolve/main/backend/core/loader.py
8.63 kB
| import os | |
| import openpyxl | |
| import xlrd | |
| from collections import defaultdict | |
| FIELD_NAMES = { | |
| "supply": "供电方式", | |
| "voltage": "输入电压(V)", | |
| "current": "输入电流(A)", | |
| "power": "输入功率(W)", | |
| "battery": "电池容量(mAh)", | |
| "removable": "电池是否可拆卸", | |
| "psu_note": "电源说明", | |
| "device_note": "设备说明", | |
| } | |
| def load_excel_grouped(path: str) -> dict: | |
| """Load power parameters from Excel, grouped by product model.""" | |
| wb = openpyxl.load_workbook(path, data_only=True) | |
| ws = wb[wb.sheetnames[0]] | |
| products = defaultdict(list) | |
| current_category = "" | |
| current_model = "" | |
| for row in ws.iter_rows(min_row=3, max_row=ws.max_row, values_only=True): | |
| values = [str(v) if v is not None else "" for v in row] | |
| seq, category, model, *rest = values[:11] | |
| category = category.strip() | |
| model = model.strip() | |
| if category: | |
| current_category = category | |
| if model: | |
| current_model = model | |
| seq = seq.strip() | |
| if not seq or not current_model: | |
| continue | |
| supply = rest[0] if len(rest) > 0 else "" | |
| voltage = rest[1] if len(rest) > 1 else "" | |
| current = rest[2] if len(rest) > 2 else "" | |
| power = rest[3] if len(rest) > 3 else "" | |
| battery = rest[4] if len(rest) > 4 else "" | |
| removable = rest[5] if len(rest) > 5 else "" | |
| psu_note = rest[6] if len(rest) > 6 else "" | |
| device_note = rest[7] if len(rest) > 7 else "" | |
| products[current_model].append({ | |
| "category": current_category, | |
| "supply": supply, | |
| "voltage": voltage, | |
| "current": current, | |
| "power": power, | |
| "battery": battery, | |
| "removable": removable, | |
| "psu_note": psu_note, | |
| "device_note": device_note, | |
| }) | |
| return dict(products) | |
| def format_product_data(model: str, rows: list[dict]) -> str: | |
| """Format power parameter rows into structured text.""" | |
| lines = [f"产品型号:{model}", f"产品分类:{rows[0]['category']}", ""] | |
| for i, r in enumerate(rows): | |
| lines.append(f"--- 供电方案 {i + 1} ---") | |
| for k, v in r.items(): | |
| if k == "category": | |
| continue | |
| if v and v.strip(): | |
| label = FIELD_NAMES.get(k, k) | |
| lines.append(f"{label}:{v}") | |
| return "\n".join(lines) | |
| def read_spec_excel(path: str) -> dict: | |
| """Read key-value spec sheet from .xls/.xlsx.""" | |
| params = {} | |
| ext = os.path.splitext(path)[1].lower() | |
| prev_key = None | |
| header_key = None | |
| def add(k, v): | |
| params[k] = v | |
| return k | |
| def append(k, v): | |
| params[k] += "、" + v | |
| if ext == ".xlsx": | |
| wb = openpyxl.load_workbook(path, data_only=True) | |
| ws = wb[wb.sheetnames[0]] | |
| for row in ws.iter_rows(min_row=1, max_row=ws.max_row, values_only=True): | |
| k = str(row[0]).strip() if row[0] is not None else "" | |
| v = str(row[1]).strip() if len(row) >= 2 and row[1] is not None else "" | |
| if k and not k.startswith("="): | |
| if v: | |
| header_key = add(k, v) | |
| elif header_key: | |
| append(header_key, k) | |
| prev_key = k | |
| elif not k and v and prev_key: | |
| if prev_key in params: | |
| params[prev_key] += ";" + v | |
| elif ext == ".xls": | |
| wb = xlrd.open_workbook(path) | |
| ws = wb.sheet_by_index(0) | |
| for r in range(ws.nrows): | |
| k = str(ws.cell_value(r, 0)).strip() | |
| v = str(ws.cell_value(r, 1)).strip() if ws.ncols >= 2 else "" | |
| if k and not k.startswith("="): | |
| if v: | |
| header_key = add(k, v) | |
| elif header_key: | |
| append(header_key, k) | |
| prev_key = k | |
| elif not k and v and prev_key: | |
| if prev_key in params: | |
| params[prev_key] += ";" + v | |
| return params | |
| def read_spec_pdf(path: str) -> dict: | |
| """Extract text from PDF specs and convert to key-value dict. | |
| PDFs with tabular data are parsed line-by-line, heuristically split at ':' or whitespace gaps. | |
| """ | |
| try: | |
| import pdfplumber | |
| except ImportError: | |
| try: | |
| import pypdf | |
| return _read_pdf_pypdf(path) | |
| except ImportError: | |
| print(f"[loader] 未安装 pdfplumber 或 pypdf,跳过 PDF: {path}") | |
| return {} | |
| params = {} | |
| with pdfplumber.open(path) as pdf: | |
| text_lines = [] | |
| for page in pdf.pages: | |
| text = page.extract_text() | |
| if text: | |
| text_lines.extend(text.split("\n")) | |
| for line in text_lines: | |
| line = line.strip() | |
| if not line: | |
| continue | |
| # Heuristic: split on ":" or ":" to find key-value pairs | |
| for sep in [":", ":"]: | |
| if sep in line: | |
| parts = line.split(sep, 1) | |
| key = parts[0].strip() | |
| val = parts[1].strip() | |
| if key and val and len(key) < 50 and len(val) < 200: | |
| params[key] = val | |
| break | |
| return params | |
| def _read_pdf_pypdf(path: str) -> dict: | |
| """Fallback PDF reader using pypdf.""" | |
| from pypdf import PdfReader | |
| reader = PdfReader(path) | |
| params = {} | |
| for page in reader.pages: | |
| text = page.extract_text() | |
| if not text: | |
| continue | |
| for line in text.split("\n"): | |
| line = line.strip() | |
| if not line: | |
| continue | |
| for sep in [":", ":"]: | |
| if sep in line: | |
| parts = line.split(sep, 1) | |
| key = parts[0].strip() | |
| val = parts[1].strip() | |
| if key and val and len(key) < 50 and len(val) < 200: | |
| params[key] = val | |
| break | |
| return params | |
| def read_spec_docx(path: str) -> dict: | |
| """Extract key-value pairs from Word spec documents. | |
| Uses similar heuristic as PDF: splits lines at ':' or ':'. | |
| """ | |
| from docx import Document as DocxDocument | |
| doc = DocxDocument(path) | |
| params = {} | |
| for p in doc.paragraphs: | |
| line = p.text.strip() | |
| if not line: | |
| continue | |
| for sep in [":", ":"]: | |
| if sep in line: | |
| parts = line.split(sep, 1) | |
| key = parts[0].strip() | |
| val = parts[1].strip() | |
| if key and val and len(key) < 50 and len(val) < 200: | |
| params[key] = val | |
| break | |
| # Also extract from tables | |
| for table in doc.tables: | |
| for row in table.rows: | |
| cells = [c.text.strip() for c in row.cells] | |
| if len(cells) >= 2: | |
| k, v = cells[0], cells[1] | |
| if k and v and len(k) < 50: | |
| params[k] = v | |
| return params | |
| def extract_text(path: str) -> str: | |
| """Extract full raw text from any supported document (PDF, Word, TXT).""" | |
| ext = os.path.splitext(path)[1].lower() | |
| if ext == ".pdf": | |
| import pdfplumber | |
| text = "" | |
| with pdfplumber.open(path) as pdf: | |
| for page in pdf.pages: | |
| t = page.extract_text() | |
| if t: | |
| text += t + "\n\n" | |
| return text.strip() | |
| elif ext == ".docx": | |
| from docx import Document as DocxDocument | |
| doc = DocxDocument(path) | |
| text = "\n".join(p.text for p in doc.paragraphs if p.text.strip()) | |
| # Tables | |
| for table in doc.tables: | |
| for row in table.rows: | |
| text += "\n" + "\t".join(c.text.strip() for c in row.cells) | |
| return text.strip() | |
| elif ext == ".txt": | |
| with open(path, "r", encoding="utf-8", errors="replace") as f: | |
| return f.read().strip() | |
| raise ValueError(f"不支持的文件格式: {ext}") | |
| def load_document(path: str): | |
| """Auto-detect format and load a document. | |
| Returns a dict of key-value params for specs, or grouped products for power params. | |
| """ | |
| fname = os.path.basename(path).lower() | |
| ext = os.path.splitext(path)[1].lower() | |
| if ext in (".xlsx", ".xls"): | |
| if "电源" in fname or "power" in fname: | |
| return load_excel_grouped(path) | |
| return read_spec_excel(path) | |
| elif ext == ".pdf": | |
| return read_spec_pdf(path) | |
| elif ext == ".docx": | |
| return read_spec_docx(path) | |
| else: | |
| raise ValueError(f"不支持的文件格式: {ext}") | |