| """ |
| core.py |
| Application orchestration |
| """ |
|
|
| from __future__ import annotations |
|
|
| import tempfile |
| import zipfile |
| from pathlib import Path |
|
|
| from builder import ( |
| build_markdown, |
| build_xml, |
| split_output, |
| ) |
| from reader import load_files |
| from scanner import ( |
| scan_files, |
| build_tree_text, |
| ) |
| from statistics import ( |
| build_statistics, |
| statistics_markdown, |
| ) |
|
|
|
|
| def extract_zip(zip_path: str) -> Path: |
| """ |
| Extract uploaded ZIP into temp directory. |
| """ |
|
|
| temp_dir = Path(tempfile.mkdtemp()) |
|
|
| with zipfile.ZipFile(zip_path, "r") as z: |
| z.extractall(temp_dir) |
|
|
| items = list(temp_dir.iterdir()) |
|
|
| if len(items) == 1 and items[0].is_dir(): |
| return items[0] |
|
|
| return temp_dir |
|
|
|
|
| def build_context( |
| zip_path: str, |
| ignored_dirs: str, |
| allowed_extensions: set[str] | None, |
| max_size_mb: float, |
| output_format: str, |
| max_tokens: int, |
| include_hash: bool, |
| ): |
|
|
| root = extract_zip(zip_path) |
|
|
| ignore = { |
| x.strip() |
| for x in ignored_dirs.split(",") |
| if x.strip() |
| } |
|
|
| files = scan_files( |
| root=root, |
| extra_ignore_dirs=ignore, |
| max_size_mb=max_size_mb, |
| allowed_extensions=allowed_extensions, |
| ) |
|
|
| contents = load_files(files) |
|
|
| stats = build_statistics( |
| files, |
| contents, |
| ) |
|
|
| if output_format.lower() == "xml": |
| text = build_xml( |
| root, |
| contents, |
| include_hash, |
| ) |
| ext = "xml" |
|
|
| else: |
|
|
| text = build_markdown( |
| root, |
| contents, |
| include_hash, |
| ) |
|
|
| ext = "md" |
|
|
| chunks = split_output( |
| text, |
| max_tokens, |
| ) |
|
|
| tree = build_tree_text( |
| root, |
| files, |
| ) |
|
|
| preview = text[:3000] |
|
|
| return { |
| "statistics": statistics_markdown(stats), |
| "tree": tree, |
| "preview": preview, |
| "chunks": chunks, |
| "extension": ext, |
| } |