space-review / source_context.py
fffiloni's picture
Attach relevant public source excerpts to Inkling reviews
a0f7e6c verified
Raw History Blame Contribute Delete
7.37 kB
import asyncio
import json
import re
from dataclasses import dataclass
from pathlib import PurePosixPath
from urllib.parse import quote, urlsplit
import httpx
from capture import SPACE_PATH, parse_url
HUB = "https://huggingface.co"
MAX_FILE_BYTES = 180_000
SOURCE_LIMIT = 6_000
CODE_EXTENSIONS = {".py", ".css", ".html", ".js", ".jsx", ".ts", ".tsx", ".svelte", ".vue"}
SKIP_DIRECTORIES = {"build", "dist", "fixtures", "node_modules", "tests", "vendor"}
COMPONENT = re.compile(r"\bgr\.(?:Blocks|HTML|Button|Row|Column|Textbox|Markdown)\b|<main\b|<h1\b|:root\s*\{|@media\b")
@dataclass(frozen=True)
class Snippet:
path: str
start_line: int
end_line: int
text: str
@dataclass(frozen=True)
class SourceContext:
repo: str
revision: str
snippets: tuple[Snippet, ...]
def link(self, path, line):
return f"{HUB}/spaces/{quote(self.repo, safe='/')}/blob/{self.revision}/{quote(path, safe='/')}#L{line}"
async def hub_json(client, path, params=None):
try:
async with client.stream("GET", f"{HUB}/api/spaces{path}", params=params) as response:
response.raise_for_status()
data = bytearray()
async for chunk in response.aiter_bytes():
data.extend(chunk)
if len(data) > 750_000:
return None
return json.loads(data)
except (httpx.HTTPError, ValueError):
return None
async def find_repo(client, source_url, host):
_, repo = parse_url(source_url)
if not repo:
slug = host.removesuffix(".hf.space")
async def search(owner, name):
hits = await hub_json(client, "", {"author": owner, "search": name.split("-", 1)[0], "limit": 25})
for hit in hits or []:
space_id = hit.get("id", "")
subdomain = re.sub(r"[^a-z0-9-]", "-", space_id.lower())
if subdomain == slug and SPACE_PATH.fullmatch(f"/spaces/{space_id}"):
return space_id
return None
parts = slug.split("-")
matches = await asyncio.gather(*(
search("-".join(parts[:i]), "-".join(parts[i:])) for i in range(1, min(len(parts), 11))
))
repo = next((match for match in matches if match), None)
if not repo:
return None
details = await hub_json(client, f"/{quote(repo, safe='/')}", {"blobs": "true"})
if not details or details.get("private") or details.get("visibility", "public") != "public":
return None
actual = details.get("host", "")
if urlsplit(actual if "://" in actual else f"https://{actual}").hostname != host:
return None
if not re.fullmatch(r"[0-9a-f]{40}", details.get("sha", "")):
return None
return details
def source_files(details):
entry = (details.get("cardData") or {}).get("app_file") or "app.py"
candidates = []
for item in details.get("siblings") or []:
path = item.get("rfilename", "")
location = PurePosixPath(path)
size = item.get("size")
if (location.suffix.lower() not in CODE_EXTENSIONS or not isinstance(size, int) or not 0 < size <= MAX_FILE_BYTES
or location.is_absolute() or any(part.startswith(".") or part in SKIP_DIRECTORIES for part in location.parts)
or re.search(r"(?:\.min\.|\.bundle\.|^test_|^secrets?\.|^credentials?\.)", location.name.lower())):
continue
if location.suffix == ".py" and path != entry and not re.search(r"(?:app|ui|layout|view|frontend)", path.lower()):
continue
priority = (20 if path == entry else 0) + (8 if location.suffix in {".css", ".html"} else 0)
if location.stem.lower() in {"app", "index", "main", "style", "styles", "layout"}:
priority += 6
candidates.append((-priority, len(location.parts), path))
return [path for _, _, path in sorted(candidates)[:8]]
async def read_file(client, repo, revision, path):
url = f"{HUB}/spaces/{quote(repo, safe='/')}/raw/{revision}/{quote(path, safe='/')}"
try:
async with client.stream("GET", url) as response:
response.raise_for_status()
data = bytearray()
async for chunk in response.aiter_bytes():
data.extend(chunk)
if len(data) > MAX_FILE_BYTES:
return ""
result = data.decode("utf-8")
return "" if "\x00" in result or result.startswith("version https://git-lfs.github.com/spec/") else result
except (httpx.HTTPError, UnicodeError):
return ""
def select_snippets(files, captures):
labels, selectors = set(), set()
for capture in captures:
strings = capture.evidence.get("headings", []) + [c["label"] for c in capture.evidence.get("controls", [])]
labels.update(label.casefold().strip() for label in strings if 5 <= len(label) <= 100)
selectors.update(value for value in capture.evidence.get("ui_selectors", []) if len(value) >= 5)
hooks = [re.compile(rf"(?<![\w-]){re.escape(value[1:])}(?![\w-])") for value in sorted(selectors)]
candidates = []
for order, (path, code) in enumerate(files):
lines = code.splitlines()
if not lines:
continue
for index, line in enumerate(lines):
if len(line) > 650:
continue
words = " ".join(re.sub(r"<[^>]+>", " ", line).casefold().split())
score = 10 * any(label in words for label in labels) + 6 * any(hook.search(line) for hook in hooks)
if score or COMPONENT.search(line):
candidates.append((-score, order, index, path, lines))
chosen, ranges = [], {}
remaining = SOURCE_LIMIT
for _, _, index, path, lines in sorted(candidates):
if remaining <= 0 or len(chosen) == 9:
break
start, stop = max(0, index - 2), min(len(lines), index + 4)
used = ranges.setdefault(path, [])
if len(used) >= 3 or any(start < end and stop > begin for begin, end in used):
continue
if any(len(line) > 650 for line in lines[start:stop]):
start, stop = index, index + 1
excerpt = "\n".join(f"{i + 1}: {lines[i]}" for i in range(start, stop))
if len(excerpt) <= remaining:
chosen.append(Snippet(path, start + 1, stop, excerpt))
used.append((start, stop))
remaining -= len(excerpt)
return tuple(sorted(chosen, key=lambda item: (item.path, item.start_line)))
async def load_source_context(source_url, target, captures):
try:
async with asyncio.timeout(9), httpx.AsyncClient(timeout=4, follow_redirects=False, trust_env=False) as client:
details = await find_repo(client, source_url, urlsplit(target).hostname or "")
if not details:
return None
repo, revision = details["id"], details["sha"]
if not SPACE_PATH.fullmatch(f"/spaces/{repo}"):
return None
paths = source_files(details)
texts = await asyncio.gather(*(read_file(client, repo, revision, path) for path in paths))
snippets = select_snippets(zip(paths, texts), captures)
return SourceContext(repo, revision, snippets) if snippets else None
except (TimeoutError, KeyError, TypeError, AttributeError):
return None