Spaces:
Sleeping
Sleeping
Download core/ingest.py from MustafaHussein/te-assistant: direct link, hf CLI and curl.
- Browser
- Download file 4.82 kB
-
https://huggingface.co/spaces/MustafaHussein/te-assistant/resolve/main/core/ingest.py
- Command line
-
hf download hf://spaces/MustafaHussein/te-assistant/core/ingest.py
-
curl -L -o ingest.py https://huggingface.co/spaces/MustafaHussein/te-assistant/resolve/main/core/ingest.py
4.82 kB
| """Turn user uploads (PDF, DOCX, TXT, HTML, images) into clean text chunks.""" | |
| import re | |
| import unicodedata | |
| from dataclasses import dataclass | |
| from pathlib import Path | |
| from typing import List, Optional, Tuple | |
| import config | |
| IMAGE_EXT = {".png", ".jpg", ".jpeg", ".bmp", ".webp", ".tif", ".tiff"} | |
| SUPPORTED_EXT = {".pdf", ".docx", ".txt", ".md", ".html", ".htm"} | IMAGE_EXT | |
| _ZERO_WIDTH = re.compile(r"[---]") | |
| _SENT_SPLIT = re.compile(r"(?<=[\.\!\?؟۔])\s+|\n+") | |
| class Chunk: | |
| text: str | |
| title: str | |
| source: str | |
| page: Optional[int] = None | |
| kind: str = "user" | |
| def clean_text(text: str) -> str: | |
| """NFKC folds Arabic presentation forms (common in PDFs) back to normal letters.""" | |
| t = unicodedata.normalize("NFKC", text or "") | |
| t = _ZERO_WIDTH.sub("", t).replace(" ", " ") | |
| t = re.sub(r"[ \t]+", " ", t) | |
| t = re.sub(r"\n\s*\n+", "\n\n", t) | |
| return t.strip() | |
| def chunk_text(text: str, size: Optional[int] = None, overlap: Optional[int] = None) -> List[str]: | |
| """Sentence-aware chunking with overlap. Works for Arabic (؟ ۔) and Latin punctuation.""" | |
| size = size or config.CHUNK_SIZE | |
| overlap = config.CHUNK_OVERLAP if overlap is None else overlap | |
| pieces: List[str] = [] | |
| for u in (u.strip() for u in _SENT_SPLIT.split(text or "")): | |
| if not u: | |
| continue | |
| while len(u) > size: # a single very long "sentence" | |
| pieces.append(u[:size]) | |
| u = u[size:] | |
| pieces.append(u) | |
| chunks: List[str] = [] | |
| cur: List[str] = [] | |
| cur_len = 0 | |
| for p in pieces: | |
| if cur and cur_len + len(p) + 1 > size: | |
| chunks.append(" ".join(cur)) | |
| keep, kl = [], 0 | |
| for q in reversed(cur): # carry the tail over as overlap | |
| if kl + len(q) > overlap: | |
| break | |
| keep.insert(0, q) | |
| kl += len(q) + 1 | |
| cur, cur_len = keep, kl | |
| cur.append(p) | |
| cur_len += len(p) + 1 | |
| if cur: | |
| chunks.append(" ".join(cur)) | |
| return [c for c in chunks if len(c.strip()) >= 20] | |
| # ---- readers: each returns [(page_number_or_None, text), ...] --------------------- | |
| def _read_pdf(path: str) -> List[Tuple[Optional[int], str]]: | |
| import pymupdf as fitz | |
| from core import ocr | |
| out, ocr_used = [], 0 | |
| with fitz.open(path) as doc: | |
| for i, page in enumerate(doc, start=1): | |
| if i > config.MAX_PDF_PAGES: | |
| break | |
| text = page.get_text("text") or "" | |
| if len(text.strip()) < 30 and ocr_used < config.MAX_OCR_PAGES: # scanned page | |
| text = ocr.read_image_bytes(page.get_pixmap(dpi=150).tobytes("png")) | |
| ocr_used += 1 | |
| out.append((i, text)) | |
| return out | |
| def _read_docx(path: str) -> List[Tuple[Optional[int], str]]: | |
| import docx | |
| d = docx.Document(path) | |
| parts = [p.text for p in d.paragraphs if p.text.strip()] | |
| for table in d.tables: | |
| for row in table.rows: | |
| cells = [c.text.strip() for c in row.cells if c.text.strip()] | |
| if cells: | |
| parts.append(" | ".join(cells)) | |
| return [(None, "\n".join(parts))] | |
| def _read_text(path: str) -> str: | |
| raw = Path(path).read_bytes() | |
| for enc in ("utf-8-sig", "utf-16", "cp1256", "latin-1"): | |
| try: | |
| return raw.decode(enc) | |
| except (UnicodeDecodeError, UnicodeError): | |
| continue | |
| return raw.decode("utf-8", errors="ignore") | |
| def _read_html(path: str) -> List[Tuple[Optional[int], str]]: | |
| from bs4 import BeautifulSoup | |
| soup = BeautifulSoup(_read_text(path), "lxml") | |
| for t in soup(["script", "style", "noscript", "svg", "iframe", "nav", "footer", "form"]): | |
| t.decompose() | |
| return [(None, soup.get_text("\n"))] | |
| def extract_pages(path: str) -> List[Tuple[Optional[int], str]]: | |
| ext = Path(path).suffix.lower() | |
| if ext == ".pdf": | |
| return _read_pdf(path) | |
| if ext == ".docx": | |
| return _read_docx(path) | |
| if ext in (".txt", ".md"): | |
| return [(None, _read_text(path))] | |
| if ext in (".html", ".htm"): | |
| return _read_html(path) | |
| if ext in IMAGE_EXT: | |
| from core import ocr | |
| return [(None, ocr.read_image(path))] | |
| raise ValueError(f"Unsupported file type '{ext}'. Supported: PDF, DOCX, TXT, HTML, PNG/JPG.") | |
| def ingest_file(path: str) -> List[Chunk]: | |
| name = Path(path).name | |
| chunks: List[Chunk] = [] | |
| for page, text in extract_pages(path): | |
| for c in chunk_text(clean_text(text)): | |
| chunks.append(Chunk(text=c, title=name, source=name, page=page, kind="user")) | |
| if len(chunks) >= config.MAX_CHUNKS_PER_FILE: | |
| return chunks | |
| if not chunks: | |
| raise ValueError("No readable text found in this file.") | |
| return chunks | |