Spaces:
Sleeping
Sleeping
Upload summaries.py
Browse files2 unmodified lines34567891011121314151617181920212223242526272829303132333435363738394041421 unmodified line44454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711722 unmodified linesimport jsonimport osimport refrom pathlib import Pathfrom huggingface_hub import hf_hub_downloadfrom local_rag.config import LocalRagConfigTITLE_PATTERN = re.compile(r"\*\*Title:\*\*\s*(.+)", re.MULTILINE)_FILENAME_TITLE = re.compile(r"^.+?\s-\s\d{4}\s-\s(.+)$")_FILENAME_YEAR = re.compile(r"^.+?\s-\s(\d{4})\s-\s")HF_DATASET_REPO = os.getenv("WATERSCOPE_DATASET_REPO", "EnvironmentalAI/WaterScopeAI-Data")HF_SUMMARY_PREFIX = os.getenv("WATERSCOPE_SUMMARY_PREFIX", "Summary")HF_SUMMARY_CACHE = Path(os.getenv("WATERSCOPE_SUMMARY_CACHE", "/tmp/waterscope-summary-cache")).expanduser().resolve()HF_SUMMARY_ON_DEMAND = os.getenv("WATERSCOPE_SUMMARY_ON_DEMAND", "1").lower() in {"1", "true", "yes"}def _year_from_filename(file_name: str) -> str | None:match = _FILENAME_YEAR.match(Path(file_name).name)return match.group(1) if match else Nonedef _download_cloud_summary(file_name: str) -> Path | None:"""Download one summary from the HF Dataset and cache it locally."""if not HF_SUMMARY_ON_DEMAND:return Noneyear = _year_from_filename(file_name)if not year:return Nonerepo_file = f"{HF_SUMMARY_PREFIX}/{year}/{Path(file_name).name}"try:downloaded = hf_hub_download(repo_id=HF_DATASET_REPO,1 unmodified linefilename=repo_file,local_dir=str(HF_SUMMARY_CACHE),)except Exception:return Nonepath = Path(downloaded)return path if path.is_file() else Nonedef summary_search_dirs() -> list[Path]:"""Directories to search for summary .txt files (first match wins)."""dirs: list[Path] = []for raw in (os.getenv("PAPER_SUMMARIES_DIRS") or "").split(":"):raw = raw.strip()if raw:dirs.append(Path(raw).expanduser().resolve())override = os.getenv("PAPER_SUMMARIES_DIR")if override:dirs.append(Path(override).expanduser().resolve())project_root = Path(__file__).resolve().parents[1]dirs.append(project_root / "paper_summaries")unique: list[Path] = []seen: set[str] = set()for path in dirs:key = str(path)if key in seen:continueseen.add(key)unique.append(path)return uniquedef summaries_dir() -> Path:for path in summary_search_dirs():if path.exists():return pathreturn Path(__file__).resolve().parents[1] / "paper_summaries"def _manifest_path(config: LocalRagConfig | None = None) -> Path:cfg = config or LocalRagConfig.from_env()return cfg.manifest_pathdef load_manifest(config: LocalRagConfig | None = None) -> dict:path = _manifest_path(config)if not path.exists():raise FileNotFoundError(f"Manifest not found: {path}. Rebuild local_rag_data/manifest.json first.")return json.loads(path.read_text(encoding="utf-8"))def title_from_filename(file_name: str) -> str:stem = Path(file_name).stemmatch = _FILENAME_TITLE.match(stem)if match:return match.group(1).strip()return stemdef extract_title(file_name: str, summary: str | None = None) -> str:if summary:match = TITLE_PATTERN.search(summary)if match:return match.group(1).strip()return title_from_filename(file_name)def summary_path(file_name: str) -> Path | None:# Preserve existing local behavior first.for root in summary_search_dirs():candidate = root / file_nameif candidate.exists():return candidate# Cloud production fallback: fetch only the requested summary.return _download_cloud_summary(file_name)def load_summary(file_name: str) -> str | None:path = summary_path(file_name)if path is None:return Nonereturn path.read_text(encoding="utf-8")def list_papers(config: LocalRagConfig | None = None) -> list[dict]:"""List indexed papers without reading every summary file into memory."""manifest = load_manifest(config)papers: list[dict] = []for entry in manifest.get("files", []):file_name = entry["file_name"]papers.append({"document_id": entry["document_id"],"file_name": file_name,"title": title_from_filename(file_name),"chunk_count": entry.get("chunk_count", 0),"has_summary": summary_path(file_name) is not None,})papers.sort(key=lambda item: item["title"].lower())return papersdef summaries_for_documents(document_ids: list[str], config: LocalRagConfig | None = None) -> list[dict]:manifest = load_manifest(config)by_id = {entry["document_id"]: entry for entry in manifest.get("files", [])}selected: list[dict] = []for document_id in document_ids:entry = by_id.get(document_id)if not entry:continuefile_name = entry["file_name"]summary = load_summary(file_name)if not summary:continueselected.append({"document_id": document_id,"title": extract_title(file_name, summary),"file_name": file_name,"text": summary,})return selected2 unmodified lines345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091921 unmodified line9495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773782 unmodified linesimport jsonimport osimport reimport unicodedatafrom pathlib import Pathfrom huggingface_hub import hf_hub_downloadfrom local_rag.config import LocalRagConfigTITLE_PATTERN = re.compile(r"\*\*Title:\*\*\s*(.+)", re.MULTILINE)_FILENAME_TITLE = re.compile(r"^.+?\s-\s\d{4}\s-\s(.+)$")_FILENAME_YEAR = re.compile(r"^.+?\s-\s(\d{4})\s-\s")HF_DATASET_REPO = os.getenv("WATERSCOPE_DATASET_REPO","EnvironmentalAI/WaterScopeAI-Data",)HF_SUMMARY_PREFIX = os.getenv("WATERSCOPE_SUMMARY_PREFIX","Summary",)HF_SUMMARY_CACHE = Path(os.getenv("WATERSCOPE_SUMMARY_CACHE","/tmp/waterscope-summary-cache",)).expanduser().resolve()HF_SUMMARY_ON_DEMAND = os.getenv("WATERSCOPE_SUMMARY_ON_DEMAND","1",).lower() in {"1","true","yes",}def _normalize_filename(file_name: str) -> str:"""Normalize filenames so visually identical Unicode forms match.Example:TürkiyeTürkiyeNFKC is also used by the paper figure matching code."""name = Path(file_name or "").name.strip()return unicodedata.normalize("NFKC", name)def _year_from_filename(file_name: str) -> str | None:safe_name = _normalize_filename(file_name)match = _FILENAME_YEAR.match(safe_name)return match.group(1) if match else Nonedef _download_cloud_summary(file_name: str) -> Path | None:"""Download one summary from the HF Dataset and cache it locally.The requested filename is Unicode-normalized before constructingthe Hugging Face Dataset path."""if not HF_SUMMARY_ON_DEMAND:return Nonesafe_name = _normalize_filename(file_name)year = _year_from_filename(safe_name)if not year:return Nonerepo_file = (f"{HF_SUMMARY_PREFIX}/"f"{year}/"f"{safe_name}")try:downloaded = hf_hub_download(repo_id=HF_DATASET_REPO,1 unmodified linefilename=repo_file,local_dir=str(HF_SUMMARY_CACHE),)except Exception as exc:print(f"[SUMMARY DOWNLOAD ERROR] "f"{repo_file}: {repr(exc)}")return Nonepath = Path(downloaded)return path if path.is_file() else Nonedef summary_search_dirs() -> list[Path]:"""Directories to search for summary .txt files (first match wins)."""dirs: list[Path] = []for raw in (os.getenv("PAPER_SUMMARIES_DIRS") or "").split(":"):raw = raw.strip()if raw:dirs.append(Path(raw).expanduser().resolve())override = os.getenv("PAPER_SUMMARIES_DIR")if override:dirs.append(Path(override).expanduser().resolve())project_root = Path(__file__).resolve().parents[1]dirs.append(project_root / "paper_summaries")unique: list[Path] = []seen: set[str] = set()for path in dirs:key = str(path)if key in seen:continueseen.add(key)unique.append(path)return uniquedef summaries_dir() -> Path:for path in summary_search_dirs():if path.exists():return pathreturn (Path(__file__).resolve().parents[1]/ "paper_summaries")def _manifest_path(config: LocalRagConfig | None = None,) -> Path:cfg = config or LocalRagConfig.from_env()return cfg.manifest_pathdef load_manifest(config: LocalRagConfig | None = None,) -> dict:path = _manifest_path(config)if not path.exists():raise FileNotFoundError(f"Manifest not found: {path}. ""Rebuild local_rag_data/manifest.json first.")return json.loads(path.read_text(encoding="utf-8"))def title_from_filename(file_name: str) -> str:stem = Path(file_name).stemmatch = _FILENAME_TITLE.match(stem)if match:return match.group(1).strip()return stemdef extract_title(file_name: str,summary: str | None = None,) -> str:if summary:match = TITLE_PATTERN.search(summary)if match:return match.group(1).strip()return title_from_filename(file_name)def _find_normalized_local_file(directory: Path,file_name: str,) -> Path | None:"""Find a locally cached/available summary using Unicode-normalizedexact filename matching.No fuzzy or prefix matching is used."""if not directory.is_dir():return Nonesafe_name = _normalize_filename(file_name)# Fast exact lookup first.candidate = directory / safe_nameif candidate.is_file():return candidate# Unicode-normalized fallback.target = safe_name.casefold()try:for path in directory.iterdir():if not path.is_file():continueexisting_name = _normalize_filename(path.name)if existing_name.casefold() == target:return pathexcept OSError:return Nonereturn Nonedef summary_path(file_name: str) -> Path | None:"""Resolve a summary locally first, then fall back to theHugging Face Dataset.Unicode normalization is applied to filename matching."""safe_name = _normalize_filename(file_name)year = _year_from_filename(safe_name)# Preserve existing local behavior first.for root in summary_search_dirs():# Flat folder layout.found = _find_normalized_local_file(root,safe_name,)if found is not None:return found# Also support year-organized local/cache folders.if year:found = _find_normalized_local_file(root / year,safe_name,)if found is not None:return found# Cloud production fallback:# fetch only the requested summary.return _download_cloud_summary(safe_name)def load_summary(file_name: str) -> str | None:path = summary_path(file_name)if path is None:return Nonereturn path.read_text(encoding="utf-8")def list_papers(config: LocalRagConfig | None = None,) -> list[dict]:"""List indexed papers without reading every summary file into memory."""manifest = load_manifest(config)papers: list[dict] = []for entry in manifest.get("files", []):file_name = entry["file_name"]papers.append({"document_id": entry["document_id"],"file_name": file_name,"title": title_from_filename(file_name),"chunk_count": entry.get("chunk_count",0,),"has_summary": (summary_path(file_name)is not None),})papers.sort(key=lambda item: item["title"].lower())return papersdef summaries_for_documents(document_ids: list[str],config: LocalRagConfig | None = None,) -> list[dict]:manifest = load_manifest(config)by_id = {entry["document_id"]: entryfor entry in manifest.get("files", [])}selected: list[dict] = []for document_id in document_ids:entry = by_id.get(document_id)if not entry:continuefile_name = entry["file_name"]summary = load_summary(file_name)if not summary:continueselected.append({"document_id": document_id,"title": extract_title(file_name,summary,),"file_name": file_name,"text": summary,})return selected
local_rag/summaries.py+241-35