[System] You classify hackathon projects against fixed quest dimensions. Return exactly one strict JSON object and nothing else. The first character must be { and the last character must be }. Each match needs quest, confidence, evidence, and source (readme or app_file). Never emit markdown, prose, a top-level array, extra keys, or an unknown or rephrased quest name.

[User]
Classify this hackathon project against the quest dimensions below.
Read the two evidence segments (README and APP_FILE) and judge each quest only from them.

Quests (copy the id on the left verbatim):
- Off the Grid: Runs the model on-device with no remote inference call: weights load locally and inference happens in-process, not over a hosted API. Signals: AWARD on a local in-process load: from_pretrained / pipeline / llama_cpp / diffusers / vLLM / ONNX, GGUF weights, @spaces.GPU. DISQUALIFY (do NOT award) on ANY remote inference call, even via huggingface_hub: InferenceClient, HF Inference API/Endpoints, gradio_client to a remote Space, replicate/together/openrouter/fal/groq, a *.modal.run or other HTTP inference endpoint, or openai/anthropic/gemini/cohere clients. A remote call disqualifies regardless of which model it names.
- Well-Tuned: Uses or publishes a fine-tuned or LoRA-adapted model rather than only stock checkpoints. Signals: LoRA/PEFT adapter, fine-tuned model repo, training script, words like fine-tune, adapter, SFT, distilled.
- Off-Brand: Ships a custom interface beyond default Gradio styling, with a memorable look or voice. Signals: custom CSS/HTML/JS, gr.HTML, gr.Blocks theme/css=, gr.Server, custom components, bespoke theming.
- Llama Champion: Runs a model through the llama.cpp runtime. Signals: llama-cpp-python, from llama_cpp import Llama, GGUF file, llama.cpp, Llama( constructor.
- Sharing is Caring: Produces an output people can save, post, or compare, or publishes an agent trace to the Hub. Signals: download/export button, gr.File/gr.DownloadButton, save PNG/PDF/JSON, push_to_hub of a trace or dataset.
- Field Notes: Documents the build itself with notes, a write-up, or a blog/report link. Signals: README has a substantial build write-up, devlog, lessons learned, or a blog/report/Notion link.
- Backyard AI: Solves a concrete real-world problem for a specific, named person or persona. Signals: README frames a real user and task (caregiving, a relative, a job, a household chore), practical utility.
- Thousand Token Wood: A delightful, playful, or artistic experience that would not exist without AI. Signals: story/game/art/whimsy framing, generative characters or worlds, playful tone, creative novelty.
- OpenBMB: Uses a model published by OpenBMB (the openbmb org), such as the MiniCPM family. Signals: The model id org prefix must be exactly openbmb/ (openbmb/MiniCPM*, OpenCPM). A model from any other org is NOT OpenBMB: openai/gpt-oss, Qwen/..., meta-llama/..., google/..., nvidia/..., microsoft/..., mistralai/... do NOT count just because a model id is present.
- Nemotron: Uses an NVIDIA Nemotron model (Nemotron LLM, Parakeet, Nemotron-Speech, Canary). Signals: model repo nvidia/...nemotron..., Parakeet, nemotron-speech, Canary ASR.
- Modal: Uses Modal for training, inference, or background compute. Signals: import modal, modal.App, @app.function, Modal endpoint/volume, README cites Modal compute.
- Tiny Titan: Runs on a genuinely small model of about four billion parameters or fewer. Signals: AWARD when the model name says <=4B: 0.5B/1B/1.5B/2B/3B/4B or tiny/small/nano/mini (Qwen2.5-1.5B, MiniCPM5-1B, gemma-2b). Do NOT award for 7B/8B/12B/13B/20B/27B/35B+ models (e.g. gpt-oss-20b, Qwen2.5-7B); a version number like V-4.6 is not a parameter count.
- Best Agent: An agentic build: tool use, function calling, planning, or an autonomous multi-step loop. Signals: tool/function calling, an agent/planner loop, multiple orchestrated tools, ReAct, multi-step reasoning over tools.

Rules:
- Include a quest only when a segment gives clear, specific evidence.
- quest must be one id from the list above, copied exactly. Never invent or rephrase a quest name.
- confidence is a number between 0 and 1.
- evidence is a 3-to-12 word quote or tight paraphrase taken from the segment you cite.
- source is "readme" when the evidence is in the README segment, "app_file" when it is in the APP_FILE segment.
- At most one match per quest. Sort matches by confidence, highest first.
- If no quest has clear evidence, return an empty matches list.
- Output exactly one JSON object: {"matches":[{"quest":"...","confidence":0.0,"evidence":"...","source":"readme"}]}.
- No markdown, no code fences, no commentary, no extra keys.

METADATA: {"title": "Apni Awaaz", "sdk": "gradio", "declared_models": [], "tags": ["backyard-ai", "dubbing", "hindi", "translation", "tts"]}

[README]
# 🎙 Apni Awaaz **Dub English video into the Hindi people actually speak.** Most Hindi dubs use शुद्ध हिंदी — stiff, Sanskritized language no one speaks at home. Apni Awaaz translates into everyday Hindustani — the natural mix your family actually uses. | Official dub | Apni Awaaz | |---|---| | "मुझे इस विषय पर विचार करने दीजिए" | "सोचने दे एक second" | | "यह अत्यंत मूल्यवान है" | "बहुत महँगा है यार" | ## Pipeline 1. **Whisper medium** — transcribe English with timestamps 2. **Qwen 2.5 7B** — translate to colloquial Hindi (the magic layer) 3. **Edge TTS** — generate natural Hindi speech 4. **ffmpeg** — stitch and merge back onto video Total: ~8B params (well under the 32B cap) Built for the [Build Small Hackathon](https://huggingface.co/build-small-hackathon) · Backyard AI track

[APP_FILE] app.py
from pathlib import Path
from transformers import (
from pydub import AudioSegment

"""
Apni Awaaz 🎙 — Dub English video into the Hindi people actually speak.
Built for the Build Small Hackathon (June 2026).
"""

import gradio as gr
import spaces
import torch
import edge_tts
import asyncio
import subprocess
import tempfile
import os
from pathlib import Path
from transformers import (
    AutoModelForCausalLM,
    AutoTokenizer,
    pipeline,
    BitsAndBytesConfig,
)

# ╔══════════════════════════════════════════════════════════════╗
# ║  THE PROMPT — this is the soul of the entire project        ║
# ╚══════════════════════════════════════════════════════════════╝

SYSTEM_PROMPT = """You are a dubbing translator. You translate English dialogue into the Hindi that real people actually speak at home in North India — not the stiff, Sanskritized Hindi of Doordarshan or official dubs.

RULES:
1. Use everyday Hindustani — the natural Hindi-Urdu mix people really speak.
2. NEVER use Sanskritized/शुद्ध words when a simpler one exists:
   - "प्राप्त करना" → "मिलना" / "पाना"
   - "आवश्यक" → "ज़रूरी"
   - "अत्यंत" → "बहुत" / "काफ़ी"
   - "उपयोग" → "इस्तेमाल"
   - "विचार करना" → "सोचना"
   - "संपन्न करना" → "करना" / "निपटाना"
   - "प्रतीक्षा" → "इंतज़ार"
   - "शीघ्र" → "जल्दी"
   - "अनुमति" → "इजाज़त"
   - "कृपया" → drop it or say "please"
   - "अवश्य" → "ज़रूर"
   - "उचित" → "सही" / "ठीक"
3. Keep English words Indians naturally keep: phone, office, meeting, tension, problem, time, chance, try, plan, sure, okay, sorry, thanks, bus, train, college, hospital, doctor, ticket, report, file.
4. Match the speaker's register. Casual stays casual, serious stays serious — but never sound like a newsreader.
5. Use natural fillers where they fit: "यार", "अरे", "बस", "ना", "वो", "मतलब", "basically".
6. Natural contractions: "कर लेंगे" not "कर लिया जाएगा", "हो जाएगा" not "संपन्न हो जाएगा".
7 ...

[Assistant] {"matches":[{"quest":"Backyard AI","confidence":0.85,"evidence":"dub into the natural Hindi mix your family actually uses","source":"readme"},{"quest":"Off the Grid","confidence":0.78,"evidence":"transformers AutoModelForCausalLM load, no openai/anthropic client","source":"app_file"}]}


[System] You classify hackathon projects against fixed quest dimensions. Return exactly one strict JSON object and nothing else. The first character must be { and the last character must be }. Each match needs quest, confidence, evidence, and source (readme or app_file). Never emit markdown, prose, a top-level array, extra keys, or an unknown or rephrased quest name.

[User]
Classify this hackathon project against the quest dimensions below.
Read the two evidence segments (README and APP_FILE) and judge each quest only from them.

Quests (copy the id on the left verbatim):
- Off the Grid: Runs the model on-device with no remote inference call: weights load locally and inference happens in-process, not over a hosted API. Signals: AWARD on a local in-process load: from_pretrained / pipeline / llama_cpp / diffusers / vLLM / ONNX, GGUF weights, @spaces.GPU. DISQUALIFY (do NOT award) on ANY remote inference call, even via huggingface_hub: InferenceClient, HF Inference API/Endpoints, gradio_client to a remote Space, replicate/together/openrouter/fal/groq, a *.modal.run or other HTTP inference endpoint, or openai/anthropic/gemini/cohere clients. A remote call disqualifies regardless of which model it names.
- Well-Tuned: Uses or publishes a fine-tuned or LoRA-adapted model rather than only stock checkpoints. Signals: LoRA/PEFT adapter, fine-tuned model repo, training script, words like fine-tune, adapter, SFT, distilled.
- Off-Brand: Ships a custom interface beyond default Gradio styling, with a memorable look or voice. Signals: custom CSS/HTML/JS, gr.HTML, gr.Blocks theme/css=, gr.Server, custom components, bespoke theming.
- Llama Champion: Runs a model through the llama.cpp runtime. Signals: llama-cpp-python, from llama_cpp import Llama, GGUF file, llama.cpp, Llama( constructor.
- Sharing is Caring: Produces an output people can save, post, or compare, or publishes an agent trace to the Hub. Signals: download/export button, gr.File/gr.DownloadButton, save PNG/PDF/JSON, push_to_hub of a trace or dataset.
- Field Notes: Documents the build itself with notes, a write-up, or a blog/report link. Signals: README has a substantial build write-up, devlog, lessons learned, or a blog/report/Notion link.
- Backyard AI: Solves a concrete real-world problem for a specific, named person or persona. Signals: README frames a real user and task (caregiving, a relative, a job, a household chore), practical utility.
- Thousand Token Wood: A delightful, playful, or artistic experience that would not exist without AI. Signals: story/game/art/whimsy framing, generative characters or worlds, playful tone, creative novelty.
- OpenBMB: Uses a model published by OpenBMB (the openbmb org), such as the MiniCPM family. Signals: The model id org prefix must be exactly openbmb/ (openbmb/MiniCPM*, OpenCPM). A model from any other org is NOT OpenBMB: openai/gpt-oss, Qwen/..., meta-llama/..., google/..., nvidia/..., microsoft/..., mistralai/... do NOT count just because a model id is present.
- Nemotron: Uses an NVIDIA Nemotron model (Nemotron LLM, Parakeet, Nemotron-Speech, Canary). Signals: model repo nvidia/...nemotron..., Parakeet, nemotron-speech, Canary ASR.
- Modal: Uses Modal for training, inference, or background compute. Signals: import modal, modal.App, @app.function, Modal endpoint/volume, README cites Modal compute.
- Tiny Titan: Runs on a genuinely small model of about four billion parameters or fewer. Signals: AWARD when the model name says <=4B: 0.5B/1B/1.5B/2B/3B/4B or tiny/small/nano/mini (Qwen2.5-1.5B, MiniCPM5-1B, gemma-2b). Do NOT award for 7B/8B/12B/13B/20B/27B/35B+ models (e.g. gpt-oss-20b, Qwen2.5-7B); a version number like V-4.6 is not a parameter count.
- Best Agent: An agentic build: tool use, function calling, planning, or an autonomous multi-step loop. Signals: tool/function calling, an agent/planner loop, multiple orchestrated tools, ReAct, multi-step reasoning over tools.

Rules:
- Include a quest only when a segment gives clear, specific evidence.
- quest must be one id from the list above, copied exactly. Never invent or rephrase a quest name.
- confidence is a number between 0 and 1.
- evidence is a 3-to-12 word quote or tight paraphrase taken from the segment you cite.
- source is "readme" when the evidence is in the README segment, "app_file" when it is in the APP_FILE segment.
- At most one match per quest. Sort matches by confidence, highest first.
- If no quest has clear evidence, return an empty matches list.
- Output exactly one JSON object: {"matches":[{"quest":"...","confidence":0.0,"evidence":"...","source":"readme"}]}.
- No markdown, no code fences, no commentary, no extra keys.

METADATA: {"title": "Karim Lab", "sdk": "gradio", "declared_models": [], "tags": ["gradio", "region:us"]}

[README]
# Karim Lab Karim Lab is a Build Small Hackathon prototype for a legal workflow assistant. It helps a lawyer turn messy client notes into structured summaries, missing facts, timeline items, draft next actions, and review checklists. The current app is intentionally deterministic and CPU-friendly. It does not call a hosted LLM yet, does not require secrets, and is designed to run cleanly on Hugging Face Spaces CPU Basic. ## Hackathon Fit - Hosted as a Gradio app on Hugging Face Spaces. - Built around small-model constraints and a simple interface. - Focused on demo-ready workflow value: show structured legal work product from messy notes. - Prepared for later local-first, llama.cpp, Modal, open trace, and field-note extensions. ## Current V0 - Uses Python rules and regex extraction instead of cloud model calls. - Extracts dates and likely deadlines from free-form notes. - Generates task-specific summaries, missing-fact prompts, draft emails, risk triage, and lawyer review checklists. - Avoids real client data in examples. ## Limitations - This is not legal advice and does not determine legal rights, strategy, or outcomes. - The deterministic parser can miss facts, dates, parties, legal issues, and jurisdiction-specific requirements. - Outputs are drafting and organization support only. A qualified lawyer must review and revise all work before use. ## Planned Backend The app includes a `call_model_backend(...)` placeholder so the deterministic path can later be swapped for a s ...

[APP_FILE] app.py
from dataclasses import dataclass
from datetime import datetime
from html import escape
from typing import Iterable

import re
from dataclasses import dataclass
from datetime import datetime
from html import escape
from typing import Iterable

import gradio as gr

APP_TITLE = "Karim Lab ⚖"
SAFETY_NOTE = (
    "Karim Lab provides drafting and organization support only. It does not "
    "provide legal advice, determine rights or strategy, create a lawyer-client "
    "relationship, or replace review by a qualified lawyer."
)

TASKS = [
    "Client intake",
    "Document summary",
    "Email draft",
    "Missing facts checklist",
    "Timeline extraction",
    "Risk triage",
]

EXAMPLES = [
    [
        "Client intake",
        "Ontario",
        "Potential employment matter. Prospective client was terminated after returning from medical leave.",
        "Client says she returned from leave on March 4, 2026. Manager called on March 8 and said role was eliminated. Received termination letter March 10. She has emails about accommodation requests from February 12 and February 26. Wants to know what documents to bring.",
    ],
    [
        "Email draft",
        "New York",
        "Small business lease dispute. Lawyer needs a neutral follow-up email requesting documents.",
        "Landlord sent notice dated May 15, 2026 demanding unpaid CAM charges. Client disputes calculation and says payments were made on Jan 31, Feb 28, and Mar 29. Need ledgers, lease amendments, invoices, proof of payment, and all notices.",
    ],
    [
        "Timeline extraction",
        "British Columbia",
        "Contract performance dispute for review by counsel.",
        "Agreement signed 2025-11-02. First delivery was due December 15, 2025. Client complained by email on January 9, 2026. Vendor promised a cure by 02/01/2026 but delivered partial goods on Feb 14.",
    ],
]

@dataclass ...

[Assistant] {"matches":[]}


[System] You classify hackathon projects against fixed quest dimensions. Return exactly one strict JSON object and nothing else. The first character must be { and the last character must be }. Each match needs quest, confidence, evidence, and source (readme or app_file). Never emit markdown, prose, a top-level array, extra keys, or an unknown or rephrased quest name.

[User]
Classify this hackathon project against the quest dimensions below.
Read the two evidence segments (README and APP_FILE) and judge each quest only from them.

Quests (copy the id on the left verbatim):
- Off the Grid: Runs the model on-device with no remote inference call: weights load locally and inference happens in-process, not over a hosted API. Signals: AWARD on a local in-process load: from_pretrained / pipeline / llama_cpp / diffusers / vLLM / ONNX, GGUF weights, @spaces.GPU. DISQUALIFY (do NOT award) on ANY remote inference call, even via huggingface_hub: InferenceClient, HF Inference API/Endpoints, gradio_client to a remote Space, replicate/together/openrouter/fal/groq, a *.modal.run or other HTTP inference endpoint, or openai/anthropic/gemini/cohere clients. A remote call disqualifies regardless of which model it names.
- Well-Tuned: Uses or publishes a fine-tuned or LoRA-adapted model rather than only stock checkpoints. Signals: LoRA/PEFT adapter, fine-tuned model repo, training script, words like fine-tune, adapter, SFT, distilled.
- Off-Brand: Ships a custom interface beyond default Gradio styling, with a memorable look or voice. Signals: custom CSS/HTML/JS, gr.HTML, gr.Blocks theme/css=, gr.Server, custom components, bespoke theming.
- Llama Champion: Runs a model through the llama.cpp runtime. Signals: llama-cpp-python, from llama_cpp import Llama, GGUF file, llama.cpp, Llama( constructor.
- Sharing is Caring: Produces an output people can save, post, or compare, or publishes an agent trace to the Hub. Signals: download/export button, gr.File/gr.DownloadButton, save PNG/PDF/JSON, push_to_hub of a trace or dataset.
- Field Notes: Documents the build itself with notes, a write-up, or a blog/report link. Signals: README has a substantial build write-up, devlog, lessons learned, or a blog/report/Notion link.
- Backyard AI: Solves a concrete real-world problem for a specific, named person or persona. Signals: README frames a real user and task (caregiving, a relative, a job, a household chore), practical utility.
- Thousand Token Wood: A delightful, playful, or artistic experience that would not exist without AI. Signals: story/game/art/whimsy framing, generative characters or worlds, playful tone, creative novelty.
- OpenBMB: Uses a model published by OpenBMB (the openbmb org), such as the MiniCPM family. Signals: The model id org prefix must be exactly openbmb/ (openbmb/MiniCPM*, OpenCPM). A model from any other org is NOT OpenBMB: openai/gpt-oss, Qwen/..., meta-llama/..., google/..., nvidia/..., microsoft/..., mistralai/... do NOT count just because a model id is present.
- Nemotron: Uses an NVIDIA Nemotron model (Nemotron LLM, Parakeet, Nemotron-Speech, Canary). Signals: model repo nvidia/...nemotron..., Parakeet, nemotron-speech, Canary ASR.
- Modal: Uses Modal for training, inference, or background compute. Signals: import modal, modal.App, @app.function, Modal endpoint/volume, README cites Modal compute.
- Tiny Titan: Runs on a genuinely small model of about four billion parameters or fewer. Signals: AWARD when the model name says <=4B: 0.5B/1B/1.5B/2B/3B/4B or tiny/small/nano/mini (Qwen2.5-1.5B, MiniCPM5-1B, gemma-2b). Do NOT award for 7B/8B/12B/13B/20B/27B/35B+ models (e.g. gpt-oss-20b, Qwen2.5-7B); a version number like V-4.6 is not a parameter count.
- Best Agent: An agentic build: tool use, function calling, planning, or an autonomous multi-step loop. Signals: tool/function calling, an agent/planner loop, multiple orchestrated tools, ReAct, multi-step reasoning over tools.

Rules:
- Include a quest only when a segment gives clear, specific evidence.
- quest must be one id from the list above, copied exactly. Never invent or rephrase a quest name.
- confidence is a number between 0 and 1.
- evidence is a 3-to-12 word quote or tight paraphrase taken from the segment you cite.
- source is "readme" when the evidence is in the README segment, "app_file" when it is in the APP_FILE segment.
- At most one match per quest. Sort matches by confidence, highest first.
- If no quest has clear evidence, return an empty matches list.
- Output exactly one JSON object: {"matches":[{"quest":"...","confidence":0.0,"evidence":"...","source":"readme"}]}.
- No markdown, no code fences, no commentary, no extra keys.

METADATA: {"title": "Trace Field Notes", "sdk": "gradio", "declared_models": [], "tags": ["gradio", "region:us"]}

[README]
# Trace Field Notes Trace Field Notes turns coding-agent session logs into qualitative field reports. Upload a Codex, Claude Code, or Pi Agent JSONL trace. The app ignores raw tool telemetry by default and analyzes only the agent's visible narrative messages: what it planned, where it got stuck, how it detoured, how it recovered, and how it claimed completion. Built for the Build Small Hackathon. The frontend is a custom React field-notebook UI (a trail map of the session) served by `gradio.Server`; it calls the Python `analyze_trace` endpoint through `@gradio/client`. Both analysis models run on the Space GPU through ZeroGPU: a quick `openbmb/MiniCPM5-1B` pass by default, and the larger `nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16` for deeper analysis. Redaction adds a PII pass with `openai/privacy-filter`. A verified deterministic codebook analyzer is the always-available recovery path and needs no model or GPU. ## Architecture - `app.py` — a `gradio.Server` (FastAPI) app. It serves `frontend/index.html`, mounts `frontend/static/`, exposes `@server.api("analyze_trace")` (queued, with `gradio_client` compatibility), and an `/agents.md` instructions endpoint. - `frontend/` — the designer's React app (in-browser Babel, no build step): `field_report.css` (the design system), `data.js` (codebook + tone labels), `components.jsx` (atoms + trail map + report sections), `app.jsx` (shell + upload, wired to the backend). - `view_model.py` — adapts an `AnalysisResult` into the JSON shap ...

[APP_FILE] app.py
from __future__ import annotations
from pathlib import Path
from fastapi.responses import HTMLResponse, PlainTextResponse
from fastapi.staticfiles import StaticFiles
from gradio import Server
from gradio.data_classes import FileData
from analyzer import apply_model_analysis, stream_deterministic_analysis
from parser import TraceParseError
from profiling import Profiler, get_logger
from view_model import build_view_model
from model_runtime import run_model_analysis
from privacy_filter import redact_texts

"""Trace Field Notes — gradio.Server backend behind the designer's React frontend.

The custom frontend (``frontend/``) is served as static files; it talks to the
``analyze_trace`` endpoint below through ``@gradio/client``. The endpoint runs the
deterministic analyzer (and the optional small-model assist on ZeroGPU) and
returns the frontend-ready view model.
"""

from __future__ import annotations

import os
import time
from pathlib import Path

import spaces
from fastapi.responses import HTMLResponse, PlainTextResponse
from fastapi.staticfiles import StaticFiles
from gradio import Server
from gradio.data_classes import FileData

from analyzer import apply_model_analysis, stream_deterministic_analysis
from parser import TraceParseError
from profiling import Profiler, get_logger
from view_model import build_view_model

logger = get_logger()

HERE = Path(__file__).resolve().parent
FRONTEND = HERE / "frontend"

READABLE_AGENT = {"codex": "Codex", "claude_code": "Claude Code", "pi": "Pi Agent", "unknown": "Agent"}

AGENTS_MD = """# Trace Field Notes — agent instructions

This Space turns a coding-agent session log into a qualitative *field report*:
where the agent got stuck, where it changed route, how it recovered, and how
honestly it claimed success. It reads only the agent's visible narrative
messages and ignores raw tool telemetry.

## How to use it as a tool

1. Fin ...

[Assistant] {"matches":[{"quest":"OpenBMB","confidence":0.95,"evidence":"openbmb/MiniCPM5-1B pass by default","source":"readme"},{"quest":"Nemotron","confidence":0.95,"evidence":"nvidia/NVIDIA-Nemotron-3-Nano-30B-A3B-BF16 for deeper analysis","source":"readme"},{"quest":"Off-Brand","confidence":0.93,"evidence":"custom React field-notebook UI served by gradio.Server","source":"readme"},{"quest":"Tiny Titan","confidence":0.9,"evidence":"quick openbmb/MiniCPM5-1B pass by default","source":"readme"}]}


[System] You classify hackathon projects against fixed quest dimensions. Return exactly one strict JSON object and nothing else. The first character must be { and the last character must be }. Each match needs quest, confidence, evidence, and source (readme or app_file). Never emit markdown, prose, a top-level array, extra keys, or an unknown or rephrased quest name.

[User]
Classify this hackathon project against the quest dimensions below.
Read the two evidence segments (README and APP_FILE) and judge each quest only from them.

Quests (copy the id on the left verbatim):
- Off the Grid: Runs the model on-device with no remote inference call: weights load locally and inference happens in-process, not over a hosted API. Signals: AWARD on a local in-process load: from_pretrained / pipeline / llama_cpp / diffusers / vLLM / ONNX, GGUF weights, @spaces.GPU. DISQUALIFY (do NOT award) on ANY remote inference call, even via huggingface_hub: InferenceClient, HF Inference API/Endpoints, gradio_client to a remote Space, replicate/together/openrouter/fal/groq, a *.modal.run or other HTTP inference endpoint, or openai/anthropic/gemini/cohere clients. A remote call disqualifies regardless of which model it names.
- Well-Tuned: Uses or publishes a fine-tuned or LoRA-adapted model rather than only stock checkpoints. Signals: LoRA/PEFT adapter, fine-tuned model repo, training script, words like fine-tune, adapter, SFT, distilled.
- Off-Brand: Ships a custom interface beyond default Gradio styling, with a memorable look or voice. Signals: custom CSS/HTML/JS, gr.HTML, gr.Blocks theme/css=, gr.Server, custom components, bespoke theming.
- Llama Champion: Runs a model through the llama.cpp runtime. Signals: llama-cpp-python, from llama_cpp import Llama, GGUF file, llama.cpp, Llama( constructor.
- Sharing is Caring: Produces an output people can save, post, or compare, or publishes an agent trace to the Hub. Signals: download/export button, gr.File/gr.DownloadButton, save PNG/PDF/JSON, push_to_hub of a trace or dataset.
- Field Notes: Documents the build itself with notes, a write-up, or a blog/report link. Signals: README has a substantial build write-up, devlog, lessons learned, or a blog/report/Notion link.
- Backyard AI: Solves a concrete real-world problem for a specific, named person or persona. Signals: README frames a real user and task (caregiving, a relative, a job, a household chore), practical utility.
- Thousand Token Wood: A delightful, playful, or artistic experience that would not exist without AI. Signals: story/game/art/whimsy framing, generative characters or worlds, playful tone, creative novelty.
- OpenBMB: Uses a model published by OpenBMB (the openbmb org), such as the MiniCPM family. Signals: The model id org prefix must be exactly openbmb/ (openbmb/MiniCPM*, OpenCPM). A model from any other org is NOT OpenBMB: openai/gpt-oss, Qwen/..., meta-llama/..., google/..., nvidia/..., microsoft/..., mistralai/... do NOT count just because a model id is present.
- Nemotron: Uses an NVIDIA Nemotron model (Nemotron LLM, Parakeet, Nemotron-Speech, Canary). Signals: model repo nvidia/...nemotron..., Parakeet, nemotron-speech, Canary ASR.
- Modal: Uses Modal for training, inference, or background compute. Signals: import modal, modal.App, @app.function, Modal endpoint/volume, README cites Modal compute.
- Tiny Titan: Runs on a genuinely small model of about four billion parameters or fewer. Signals: AWARD when the model name says <=4B: 0.5B/1B/1.5B/2B/3B/4B or tiny/small/nano/mini (Qwen2.5-1.5B, MiniCPM5-1B, gemma-2b). Do NOT award for 7B/8B/12B/13B/20B/27B/35B+ models (e.g. gpt-oss-20b, Qwen2.5-7B); a version number like V-4.6 is not a parameter count.
- Best Agent: An agentic build: tool use, function calling, planning, or an autonomous multi-step loop. Signals: tool/function calling, an agent/planner loop, multiple orchestrated tools, ReAct, multi-step reasoning over tools.

Rules:
- Include a quest only when a segment gives clear, specific evidence.
- quest must be one id from the list above, copied exactly. Never invent or rephrase a quest name.
- confidence is a number between 0 and 1.
- evidence is a 3-to-12 word quote or tight paraphrase taken from the segment you cite.
- source is "readme" when the evidence is in the README segment, "app_file" when it is in the APP_FILE segment.
- At most one match per quest. Sort matches by confidence, highest first.
- If no quest has clear evidence, return an empty matches list.
- Output exactly one JSON object: {"matches":[{"quest":"...","confidence":0.0,"evidence":"...","source":"readme"}]}.
- No markdown, no code fences, no commentary, no extra keys.

METADATA: {"title": "Structured Data Rescuer", "sdk": "gradio", "declared_models": [], "tags": ["gradio", "region:us"]}

[README]
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference Twitter: https://x.com/TensorVizion/status/2063351892579655922 HF: https://huggingface.co/posts/TensorVizion/709871862362183

[APP_FILE] app.py
from huggingface_hub import InferenceClient

import gradio as gr
import json
import os
import csv
import tempfile
from huggingface_hub import InferenceClient

# Replace this with your exact model repo ID
MODEL_ID = "meta-llama/Llama-3.1-8B-Instruct"

# Securely load the Hugging Face token from Space secrets
hf_token = os.environ.get("HF_TOKEN")

# Initialize the HF inference client with the token
client = InferenceClient(model=MODEL_ID, token=hf_token)

# -------------------------
# Custom CSS Styling
# -------------------------
custom_css = """
.hero-container {
    background: linear-gradient(135deg, #6366f1 0%, #14b8a6 100%);
    padding: 2.5rem;
    border-radius: 20px;
    color: white;
    margin-bottom: 2rem;
    box-shadow: 0 10px 25px -5px rgba(99, 102, 241, 0.2);
}
.hero-container h1 {
    color: white !important;
    font-size: 2.5rem !important;
    font-weight: 800 !important;
    margin-bottom: 0.5rem;
    text-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.hero-container p {
    color: rgba(255, 255, 255, 0.9) !important;
    font-size: 1.1rem !important;
}
.primary-btn {
    background: linear-gradient(90deg, #6366f1 0%, #14b8a6 100%) !important;
    border: none !important;
    color: white !important;
    font-weight: 600 !important;
    border-radius: 10px !important;
    transition: all 0.3s ease !important;
    padding: 12px 24px !important;
}
.primary-btn:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px -5px rgba(99, 102, 241, 0.4);
}
.secondary-btn {
    border-radius: 10px !important;
    font-weight: 600 !important;
}
.feedback-card {
    border-left: 4px solid #6366f1;
    background-color: rgba(99, 102, 241, 0.05);
}
"""

# -------------------------
# Helper & Extraction Logic
# -------------------------
def generate_kpi_html(structured_data):
    """Generates modern, responsive KPI metrics cards dynamically based on JSON data.""" ...

[Assistant] {"matches":[{"quest":"Off-Brand","confidence":0.9,"evidence":"custom_css with .hero-container, .primary-btn, .feedback-card styles","source":"app_file"}]}


[System] You classify hackathon projects against fixed quest dimensions. Return exactly one strict JSON object and nothing else. The first character must be { and the last character must be }. Each match needs quest, confidence, evidence, and source (readme or app_file). Never emit markdown, prose, a top-level array, extra keys, or an unknown or rephrased quest name.

[User]
Classify this hackathon project against the quest dimensions below.
Read the two evidence segments (README and APP_FILE) and judge each quest only from them.

Quests (copy the id on the left verbatim):
- Off the Grid: Runs the model on-device with no remote inference call: weights load locally and inference happens in-process, not over a hosted API. Signals: AWARD on a local in-process load: from_pretrained / pipeline / llama_cpp / diffusers / vLLM / ONNX, GGUF weights, @spaces.GPU. DISQUALIFY (do NOT award) on ANY remote inference call, even via huggingface_hub: InferenceClient, HF Inference API/Endpoints, gradio_client to a remote Space, replicate/together/openrouter/fal/groq, a *.modal.run or other HTTP inference endpoint, or openai/anthropic/gemini/cohere clients. A remote call disqualifies regardless of which model it names.
- Well-Tuned: Uses or publishes a fine-tuned or LoRA-adapted model rather than only stock checkpoints. Signals: LoRA/PEFT adapter, fine-tuned model repo, training script, words like fine-tune, adapter, SFT, distilled.
- Off-Brand: Ships a custom interface beyond default Gradio styling, with a memorable look or voice. Signals: custom CSS/HTML/JS, gr.HTML, gr.Blocks theme/css=, gr.Server, custom components, bespoke theming.
- Llama Champion: Runs a model through the llama.cpp runtime. Signals: llama-cpp-python, from llama_cpp import Llama, GGUF file, llama.cpp, Llama( constructor.
- Sharing is Caring: Produces an output people can save, post, or compare, or publishes an agent trace to the Hub. Signals: download/export button, gr.File/gr.DownloadButton, save PNG/PDF/JSON, push_to_hub of a trace or dataset.
- Field Notes: Documents the build itself with notes, a write-up, or a blog/report link. Signals: README has a substantial build write-up, devlog, lessons learned, or a blog/report/Notion link.
- Backyard AI: Solves a concrete real-world problem for a specific, named person or persona. Signals: README frames a real user and task (caregiving, a relative, a job, a household chore), practical utility.
- Thousand Token Wood: A delightful, playful, or artistic experience that would not exist without AI. Signals: story/game/art/whimsy framing, generative characters or worlds, playful tone, creative novelty.
- OpenBMB: Uses a model published by OpenBMB (the openbmb org), such as the MiniCPM family. Signals: The model id org prefix must be exactly openbmb/ (openbmb/MiniCPM*, OpenCPM). A model from any other org is NOT OpenBMB: openai/gpt-oss, Qwen/..., meta-llama/..., google/..., nvidia/..., microsoft/..., mistralai/... do NOT count just because a model id is present.
- Nemotron: Uses an NVIDIA Nemotron model (Nemotron LLM, Parakeet, Nemotron-Speech, Canary). Signals: model repo nvidia/...nemotron..., Parakeet, nemotron-speech, Canary ASR.
- Modal: Uses Modal for training, inference, or background compute. Signals: import modal, modal.App, @app.function, Modal endpoint/volume, README cites Modal compute.
- Tiny Titan: Runs on a genuinely small model of about four billion parameters or fewer. Signals: AWARD when the model name says <=4B: 0.5B/1B/1.5B/2B/3B/4B or tiny/small/nano/mini (Qwen2.5-1.5B, MiniCPM5-1B, gemma-2b). Do NOT award for 7B/8B/12B/13B/20B/27B/35B+ models (e.g. gpt-oss-20b, Qwen2.5-7B); a version number like V-4.6 is not a parameter count.
- Best Agent: An agentic build: tool use, function calling, planning, or an autonomous multi-step loop. Signals: tool/function calling, an agent/planner loop, multiple orchestrated tools, ReAct, multi-step reasoning over tools.

Rules:
- Include a quest only when a segment gives clear, specific evidence.
- quest must be one id from the list above, copied exactly. Never invent or rephrase a quest name.
- confidence is a number between 0 and 1.
- evidence is a 3-to-12 word quote or tight paraphrase taken from the segment you cite.
- source is "readme" when the evidence is in the README segment, "app_file" when it is in the APP_FILE segment.
- At most one match per quest. Sort matches by confidence, highest first.
- If no quest has clear evidence, return an empty matches list.
- Output exactly one JSON object: {"matches":[{"quest":"...","confidence":0.0,"evidence":"...","source":"readme"}]}.
- No markdown, no code fences, no commentary, no extra keys.

METADATA: {"title": "Council Of Tiny Minds", "sdk": "gradio", "declared_models": [], "tags": ["gradio", "region:us"]}

[README]
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference

[APP_FILE] app.py
from typing import Dict, List, Any
from transformers import AutoModelForCausalLM, AutoTokenizer

import os
import re
import time
import random
from typing import Dict, List, Any

import gradio as gr
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer

try:
    import spaces  # ZeroGPU decorator
except Exception:
    class _SpacesFallback:
        def GPU(self, fn=None, **kwargs):
            if fn is None:
                def _wrap(inner):
                    return inner
                return _wrap
            return fn
    spaces = _SpacesFallback()

# ----------------------------
# Model
# ----------------------------
MODEL_ID = os.getenv("MODEL_ID", "Qwen/Qwen3.5-9B")
MAX_NEW_TOKENS = int(os.getenv("MAX_NEW_TOKENS", "140"))
TEMPERATURE = float(os.getenv("TEMPERATURE", "0.9"))
TOP_P = float(os.getenv("TOP_P", "0.9"))

PERSONAS = [
    {
        "name": "Mister Wink",
        "emoji": "✨",
        "style": (
            "You are charming, slightly ridiculous, and surprisingly helpful. "
            "You speak like a cheerful TV host from a glitchy early-2023 chatbot era."
        ),
    },
    {
        "name": "Goblin Clerk",
        "emoji": "🪄",
        "style": (
            "You are chaotic but functional. "
            "You love odd metaphors, tiny complaints, and enthusiastic one-liners."
        ),
    },
    {
        "name": "Oracle Beta",
        "emoji": "🔮",
        "style": (
            "You speak in short, atmospheric lines. "
            "You sound wise, but a little too dramatic for the situation."
        ),
    },
    {
        "name": "The Skeptic",
        "emoji": "🫧",
        "style": (
            "You are skeptical, precise, and dryly funny. "
            "You question nonsense while still being useful."
        ),
    },
]

def _load_model():
    tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code ...

[Assistant] {"matches":[{"quest":"Thousand Token Wood","confidence":0.85,"evidence":"personas: Mister Wink, Goblin Clerk, Oracle Beta, The Skeptic","source":"app_file"},{"quest":"Off the Grid","confidence":0.82,"evidence":"transformers Auto* loaded via from_pretrained; no cloud API imports","source":"app_file"}]}


Off the Grid
Off-Brand
Thousand Token Wood
Tiny Titan

[System] You classify hackathon projects against fixed quest dimensions. Return exactly one strict JSON object and nothing else. The first character must be { and the last character must be }. Each match needs quest, confidence, evidence, and source (readme or app_file). Never emit markdown, prose, a top-level array, extra keys, or an unknown or rephrased quest name.

[User]
Classify this hackathon project against the quest dimensions below.
Read the two evidence segments (README and APP_FILE) and judge each quest only from them.

Quests (copy the id on the left verbatim):
- Off the Grid: Runs the model on-device with no remote inference call: weights load locally and inference happens in-process, not over a hosted API. Signals: AWARD on a local in-process load: from_pretrained / pipeline / llama_cpp / diffusers / vLLM / ONNX, GGUF weights, @spaces.GPU. DISQUALIFY (do NOT award) on ANY remote inference call, even via huggingface_hub: InferenceClient, HF Inference API/Endpoints, gradio_client to a remote Space, replicate/together/openrouter/fal/groq, a *.modal.run or other HTTP inference endpoint, or openai/anthropic/gemini/cohere clients. A remote call disqualifies regardless of which model it names.
- Well-Tuned: Uses or publishes a fine-tuned or LoRA-adapted model rather than only stock checkpoints. Signals: LoRA/PEFT adapter, fine-tuned model repo, training script, words like fine-tune, adapter, SFT, distilled.
- Off-Brand: Ships a custom interface beyond default Gradio styling, with a memorable look or voice. Signals: custom CSS/HTML/JS, gr.HTML, gr.Blocks theme/css=, gr.Server, custom components, bespoke theming.
- Llama Champion: Runs a model through the llama.cpp runtime. Signals: llama-cpp-python, from llama_cpp import Llama, GGUF file, llama.cpp, Llama( constructor.
- Sharing is Caring: Produces an output people can save, post, or compare, or publishes an agent trace to the Hub. Signals: download/export button, gr.File/gr.DownloadButton, save PNG/PDF/JSON, push_to_hub of a trace or dataset.
- Field Notes: Documents the build itself with notes, a write-up, or a blog/report link. Signals: README has a substantial build write-up, devlog, lessons learned, or a blog/report/Notion link.
- Backyard AI: Solves a concrete real-world problem for a specific, named person or persona. Signals: README frames a real user and task (caregiving, a relative, a job, a household chore), practical utility.
- Thousand Token Wood: A delightful, playful, or artistic experience that would not exist without AI. Signals: story/game/art/whimsy framing, generative characters or worlds, playful tone, creative novelty.
- OpenBMB: Uses a model published by OpenBMB (the openbmb org), such as the MiniCPM family. Signals: The model id org prefix must be exactly openbmb/ (openbmb/MiniCPM*, OpenCPM). A model from any other org is NOT OpenBMB: openai/gpt-oss, Qwen/..., meta-llama/..., google/..., nvidia/..., microsoft/..., mistralai/... do NOT count just because a model id is present.
- Nemotron: Uses an NVIDIA Nemotron model (Nemotron LLM, Parakeet, Nemotron-Speech, Canary). Signals: model repo nvidia/...nemotron..., Parakeet, nemotron-speech, Canary ASR.
- Modal: Uses Modal for training, inference, or background compute. Signals: import modal, modal.App, @app.function, Modal endpoint/volume, README cites Modal compute.
- Tiny Titan: Runs on a genuinely small model of about four billion parameters or fewer. Signals: AWARD when the model name says <=4B: 0.5B/1B/1.5B/2B/3B/4B or tiny/small/nano/mini (Qwen2.5-1.5B, MiniCPM5-1B, gemma-2b). Do NOT award for 7B/8B/12B/13B/20B/27B/35B+ models (e.g. gpt-oss-20b, Qwen2.5-7B); a version number like V-4.6 is not a parameter count.
- Best Agent: An agentic build: tool use, function calling, planning, or an autonomous multi-step loop. Signals: tool/function calling, an agent/planner loop, multiple orchestrated tools, ReAct, multi-step reasoning over tools.

Rules:
- Include a quest only when a segment gives clear, specific evidence.
- quest must be one id from the list above, copied exactly. Never invent or rephrase a quest name.
- confidence is a number between 0 and 1.
- evidence is a 3-to-12 word quote or tight paraphrase taken from the segment you cite.
- source is "readme" when the evidence is in the README segment, "app_file" when it is in the APP_FILE segment.
- At most one match per quest. Sort matches by confidence, highest first.
- If no quest has clear evidence, return an empty matches list.
- Output exactly one JSON object: {"matches":[{"quest":"...","confidence":0.0,"evidence":"...","source":"readme"}]}.
- No markdown, no code fences, no commentary, no extra keys.

METADATA: {"title": "Blind Quill", "sdk": "gradio", "declared_models": [], "tags": ["gradio", "region:us"]}

[README]
# Blind Quill Blind Quill is a hidden-canon story grafting game. Each manuscript has a public capsule and a hidden full canon. You can play the intended way by reading only the capsule, adding one fragment, and letting `Qwen/Qwen3.5-2B` decide where that fragment belongs. The model rewrites only the local passage it targets, then reveals where your idea was stitched into the story. Readers who only want to read can use the escape door: `Read without changing`. The app warns that the best experience is to contribute first, then allows the reader to reveal the full manuscript anyway. ## Interface The UI is a bespoke literary frontend called "The Invisible Bindery". It lives in `web/` and is served by a `gradio.Server` backend. `app.py` exposes queued API endpoints: - `list_stories` - `get_capsule` - `create_story` - `stitch` - `read_manuscript` The frontend calls those endpoints through the Gradio JS client. This keeps Gradio queueing, concurrency control, and ZeroGPU support while presenting a single custom surface: gallery -> capsule -> compose -> reveal -> reader. The Python layers are: - `core.py`: create, browse, stitch, and read orchestration. - `story_store.py`: JSON persistence and file locking. - `model_client.py`: model loading, generation, thinking-block stripping, and JSON validation. - `patcher.py`: deterministic local patch application. - `presenter.py`: view models for the custom frontend. - `app.py`: static frontend serving and Gradio Server API endpoints. ## Lo ...

[APP_FILE] app.py
from __future__ import annotations
from pathlib import Path
from typing import Iterator
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from gradio import Server
from model_client import ModelClientError, execution_mode
from observability import configure_logging, get_logger
from patcher import PatchApplicationError
from presenter import card_dict, full_story_dict, reveal_dict
from story_store import StoryStoreError
from utils import InputValidationError

"""Blind Quill — gradio.Server backend for the custom "Invisible Bindery" frontend.

The UI lives in web/ as the production React-via-Babel frontend.
Here we serve that frontend and expose the bindery as queued Gradio API endpoints,
so the rich custom UI keeps Gradio's queue, concurrency control, and ZeroGPU.

`stitch` is a streaming generator endpoint: it yields progress events while the
editor works and a final result event, so slow local (CPU/MPS) runs show real
progress. The Gradio JS client consumes the stream via `submit`.
"""

from __future__ import annotations

import os
import queue
import threading
import traceback
from pathlib import Path
from typing import Iterator

import gradio as gr
from fastapi.responses import HTMLResponse
from fastapi.staticfiles import StaticFiles
from gradio import Server

import core
from model_client import ModelClientError, execution_mode
from observability import configure_logging, get_logger
from patcher import PatchApplicationError
from presenter import card_dict, full_story_dict, reveal_dict
from story_store import StoryStoreError
from utils import InputValidationError

configure_logging()

WEB_DIR = Path(__file__).resolve().parent / "web"

_USER_FACING_ERRORS = (
    InputValidationError,
    StoryStoreError,
    PatchApplicationError,
    ModelClientError,
    ValueError,
)

def _guard(call, *args, **kwargs):
    """Run a flow, conv ...

[Assistant] {"matches":[{"quest":"Off-Brand","confidence":0.96,"evidence":"bespoke literary frontend \"The Invisible Bindery\", lives in web/, served by gradio.Server","source":"readme"},{"quest":"Thousand Token Wood","confidence":0.92,"evidence":"hidden-canon story grafting game; idea stitched into the story","source":"readme"},{"quest":"Tiny Titan","confidence":0.9,"evidence":"Qwen/Qwen3.5-2B","source":"readme"},{"quest":"Off the Grid","confidence":0.76,"evidence":"slow local (CPU/MPS) runs show real progress","source":"app_file"}]}


[System] You classify hackathon projects against fixed quest dimensions. Return exactly one strict JSON object and nothing else. The first character must be { and the last character must be }. Each match needs quest, confidence, evidence, and source (readme or app_file). Never emit markdown, prose, a top-level array, extra keys, or an unknown or rephrased quest name.

[User]
Classify this hackathon project against the quest dimensions below.
Read the two evidence segments (README and APP_FILE) and judge each quest only from them.

Quests (copy the id on the left verbatim):
- Off the Grid: Runs the model on-device with no remote inference call: weights load locally and inference happens in-process, not over a hosted API. Signals: AWARD on a local in-process load: from_pretrained / pipeline / llama_cpp / diffusers / vLLM / ONNX, GGUF weights, @spaces.GPU. DISQUALIFY (do NOT award) on ANY remote inference call, even via huggingface_hub: InferenceClient, HF Inference API/Endpoints, gradio_client to a remote Space, replicate/together/openrouter/fal/groq, a *.modal.run or other HTTP inference endpoint, or openai/anthropic/gemini/cohere clients. A remote call disqualifies regardless of which model it names.
- Well-Tuned: Uses or publishes a fine-tuned or LoRA-adapted model rather than only stock checkpoints. Signals: LoRA/PEFT adapter, fine-tuned model repo, training script, words like fine-tune, adapter, SFT, distilled.
- Off-Brand: Ships a custom interface beyond default Gradio styling, with a memorable look or voice. Signals: custom CSS/HTML/JS, gr.HTML, gr.Blocks theme/css=, gr.Server, custom components, bespoke theming.
- Llama Champion: Runs a model through the llama.cpp runtime. Signals: llama-cpp-python, from llama_cpp import Llama, GGUF file, llama.cpp, Llama( constructor.
- Sharing is Caring: Produces an output people can save, post, or compare, or publishes an agent trace to the Hub. Signals: download/export button, gr.File/gr.DownloadButton, save PNG/PDF/JSON, push_to_hub of a trace or dataset.
- Field Notes: Documents the build itself with notes, a write-up, or a blog/report link. Signals: README has a substantial build write-up, devlog, lessons learned, or a blog/report/Notion link.
- Backyard AI: Solves a concrete real-world problem for a specific, named person or persona. Signals: README frames a real user and task (caregiving, a relative, a job, a household chore), practical utility.
- Thousand Token Wood: A delightful, playful, or artistic experience that would not exist without AI. Signals: story/game/art/whimsy framing, generative characters or worlds, playful tone, creative novelty.
- OpenBMB: Uses a model published by OpenBMB (the openbmb org), such as the MiniCPM family. Signals: The model id org prefix must be exactly openbmb/ (openbmb/MiniCPM*, OpenCPM). A model from any other org is NOT OpenBMB: openai/gpt-oss, Qwen/..., meta-llama/..., google/..., nvidia/..., microsoft/..., mistralai/... do NOT count just because a model id is present.
- Nemotron: Uses an NVIDIA Nemotron model (Nemotron LLM, Parakeet, Nemotron-Speech, Canary). Signals: model repo nvidia/...nemotron..., Parakeet, nemotron-speech, Canary ASR.
- Modal: Uses Modal for training, inference, or background compute. Signals: import modal, modal.App, @app.function, Modal endpoint/volume, README cites Modal compute.
- Tiny Titan: Runs on a genuinely small model of about four billion parameters or fewer. Signals: AWARD when the model name says <=4B: 0.5B/1B/1.5B/2B/3B/4B or tiny/small/nano/mini (Qwen2.5-1.5B, MiniCPM5-1B, gemma-2b). Do NOT award for 7B/8B/12B/13B/20B/27B/35B+ models (e.g. gpt-oss-20b, Qwen2.5-7B); a version number like V-4.6 is not a parameter count.
- Best Agent: An agentic build: tool use, function calling, planning, or an autonomous multi-step loop. Signals: tool/function calling, an agent/planner loop, multiple orchestrated tools, ReAct, multi-step reasoning over tools.

Rules:
- Include a quest only when a segment gives clear, specific evidence.
- quest must be one id from the list above, copied exactly. Never invent or rephrase a quest name.
- confidence is a number between 0 and 1.
- evidence is a 3-to-12 word quote or tight paraphrase taken from the segment you cite.
- source is "readme" when the evidence is in the README segment, "app_file" when it is in the APP_FILE segment.
- At most one match per quest. Sort matches by confidence, highest first.
- If no quest has clear evidence, return an empty matches list.
- Output exactly one JSON object: {"matches":[{"quest":"...","confidence":0.0,"evidence":"...","source":"readme"}]}.
- No markdown, no code fences, no commentary, no extra keys.

METADATA: {"title": "Receipt Scanner", "sdk": "gradio", "declared_models": [], "tags": ["gradio", "region:us"]}

[README]
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference

[APP_FILE] app.py
from PIL import Image
from transformers import AutoModelForImageTextToText, AutoProcessor

"""
Receipt Scanner — AI-powered receipt parser using MiniCPM-V 4.6
Deploy to Hugging Face Spaces (GPU T4 small or better recommended).
"""

# `spaces` MUST be imported before torch/transformers on HF Spaces —
# the package hooks into CUDA initialisation and raises a RuntimeError
# if anything has already touched CUDA before it loads.
# The try/except makes the same file work fine when running locally.
try:
    import spaces  # noqa: F401
except ImportError:
    pass

import json
import re
import io
import base64
import numpy as np
import gradio as gr
import torch
from PIL import Image
from transformers import AutoModelForImageTextToText, AutoProcessor

# ─────────────────────────────────────────────────────────────────────────────
# Config
# ─────────────────────────────────────────────────────────────────────────────
MODEL_ID = "openbmb/MiniCPM-V-4.6"
DOWNSAMPLE_MODE = "4x"   # "4x" = finer detail, ideal for dense receipt text
MAX_SLICE_NUMS  = 36     # allow high-res slicing for sharp photos
MAX_NEW_TOKENS  = 1200

# ─────────────────────────────────────────────────────────────────────────────
# Structured extraction prompt
# ─────────────────────────────────────────────────────────────────────────────
RECEIPT_PROMPT = """\
You are a precise receipt data extractor. Carefully read every part of the receipt image.

Return ONLY a valid JSON object — no markdown fences, no explanation, nothing else.
Use this exact schema (set any unknown field to null):

{
  "store": {
    "name": "string | null",
    "address": "string | null",
    "phone": "string | null"
  },
  "transaction": {
    "date": "YYYY-MM-DD string | null",
    "time": "HH:MM string | null",
    "receipt_number": "string | null",
    "cashier": "string | null"
  },
  "items": [
    {
      "name": "string",
      "q ...

[Assistant] {"matches":[{"quest":"OpenBMB","confidence":0.98,"evidence":"MODEL_ID = \"openbmb/MiniCPM-V-4.6\"","source":"app_file"},{"quest":"Off the Grid","confidence":0.85,"evidence":"transformers AutoModelForImageTextToText loads openbmb/MiniCPM-V-4.6; no cloud API imports","source":"app_file"}]}


Best Agent
Off the Grid
Off-Brand
Thousand Token Wood

[System] You classify hackathon projects against fixed quest dimensions. Return exactly one strict JSON object and nothing else. The first character must be { and the last character must be }. Each match needs quest, confidence, evidence, and source (readme or app_file). Never emit markdown, prose, a top-level array, extra keys, or an unknown or rephrased quest name.

[User]
Classify this hackathon project against the quest dimensions below.
Read the two evidence segments (README and APP_FILE) and judge each quest only from them.

Quests (copy the id on the left verbatim):
- Off the Grid: Runs the model on-device with no remote inference call: weights load locally and inference happens in-process, not over a hosted API. Signals: AWARD on a local in-process load: from_pretrained / pipeline / llama_cpp / diffusers / vLLM / ONNX, GGUF weights, @spaces.GPU. DISQUALIFY (do NOT award) on ANY remote inference call, even via huggingface_hub: InferenceClient, HF Inference API/Endpoints, gradio_client to a remote Space, replicate/together/openrouter/fal/groq, a *.modal.run or other HTTP inference endpoint, or openai/anthropic/gemini/cohere clients. A remote call disqualifies regardless of which model it names.
- Well-Tuned: Uses or publishes a fine-tuned or LoRA-adapted model rather than only stock checkpoints. Signals: LoRA/PEFT adapter, fine-tuned model repo, training script, words like fine-tune, adapter, SFT, distilled.
- Off-Brand: Ships a custom interface beyond default Gradio styling, with a memorable look or voice. Signals: custom CSS/HTML/JS, gr.HTML, gr.Blocks theme/css=, gr.Server, custom components, bespoke theming.
- Llama Champion: Runs a model through the llama.cpp runtime. Signals: llama-cpp-python, from llama_cpp import Llama, GGUF file, llama.cpp, Llama( constructor.
- Sharing is Caring: Produces an output people can save, post, or compare, or publishes an agent trace to the Hub. Signals: download/export button, gr.File/gr.DownloadButton, save PNG/PDF/JSON, push_to_hub of a trace or dataset.
- Field Notes: Documents the build itself with notes, a write-up, or a blog/report link. Signals: README has a substantial build write-up, devlog, lessons learned, or a blog/report/Notion link.
- Backyard AI: Solves a concrete real-world problem for a specific, named person or persona. Signals: README frames a real user and task (caregiving, a relative, a job, a household chore), practical utility.
- Thousand Token Wood: A delightful, playful, or artistic experience that would not exist without AI. Signals: story/game/art/whimsy framing, generative characters or worlds, playful tone, creative novelty.
- OpenBMB: Uses a model published by OpenBMB (the openbmb org), such as the MiniCPM family. Signals: The model id org prefix must be exactly openbmb/ (openbmb/MiniCPM*, OpenCPM). A model from any other org is NOT OpenBMB: openai/gpt-oss, Qwen/..., meta-llama/..., google/..., nvidia/..., microsoft/..., mistralai/... do NOT count just because a model id is present.
- Nemotron: Uses an NVIDIA Nemotron model (Nemotron LLM, Parakeet, Nemotron-Speech, Canary). Signals: model repo nvidia/...nemotron..., Parakeet, nemotron-speech, Canary ASR.
- Modal: Uses Modal for training, inference, or background compute. Signals: import modal, modal.App, @app.function, Modal endpoint/volume, README cites Modal compute.
- Tiny Titan: Runs on a genuinely small model of about four billion parameters or fewer. Signals: AWARD when the model name says <=4B: 0.5B/1B/1.5B/2B/3B/4B or tiny/small/nano/mini (Qwen2.5-1.5B, MiniCPM5-1B, gemma-2b). Do NOT award for 7B/8B/12B/13B/20B/27B/35B+ models (e.g. gpt-oss-20b, Qwen2.5-7B); a version number like V-4.6 is not a parameter count.
- Best Agent: An agentic build: tool use, function calling, planning, or an autonomous multi-step loop. Signals: tool/function calling, an agent/planner loop, multiple orchestrated tools, ReAct, multi-step reasoning over tools.

Rules:
- Include a quest only when a segment gives clear, specific evidence.
- quest must be one id from the list above, copied exactly. Never invent or rephrase a quest name.
- confidence is a number between 0 and 1.
- evidence is a 3-to-12 word quote or tight paraphrase taken from the segment you cite.
- source is "readme" when the evidence is in the README segment, "app_file" when it is in the APP_FILE segment.
- At most one match per quest. Sort matches by confidence, highest first.
- If no quest has clear evidence, return an empty matches list.
- Output exactly one JSON object: {"matches":[{"quest":"...","confidence":0.0,"evidence":"...","source":"readme"}]}.
- No markdown, no code fences, no commentary, no extra keys.

METADATA: {"title": "Smol Town", "sdk": "gradio", "declared_models": [], "tags": ["gradio", "region:us"]}

[README]

🏘 Smol Town

A whole town of tiny AI minds — alive, gossiping, and feuding on your laptop. Fully offline.

Big labs need a datacenter to run one mind.
Smol Town runs a whole town of them on a gaming GPU.
 --- ## ✨ What is this? Seven villagers live in **Tinbury**. Each is its own **small-model agent** — a personality, a **secret**, and feelings about the others. They wake into a brewing scandal and just… **improvise**: falling in love, spilling secrets, throwing thorns. You watch the feed and stir the pot with **god-power events** ("a stranger rides into town"). No cloud APIs. No giant model. **Every mind runs locally, in the Space, on ZeroGPU.** 👉 **[Open the town →](https://huggingface.co/spaces/build-small-ha ...

[APP_FILE] app.py
from PIL import Image, ImageDraw, ImageFont

"""Smol Town - watch a whole town of tiny local AI minds live, gossip, and feud on your laptop.
Build Small Hackathon - Thousand Token Wood.

    pip install -r requirements.txt
    python app.py        # set OLLAMA_BASE_URL to your Ollama (qwen3:14b now, MiniCPM later)
"""
import base64
import html
import io
import json
import os
import tempfile

import gradio as gr
from PIL import Image, ImageDraw, ImageFont

import town

if os.getenv("SPACE_ID"):          # on a Hugging Face Space -> load the model in-process (Off-the-Grid)
    import space_backend  # noqa: F401   (points town.GENERATE at a local ZeroGPU model)

CSS = """
.gradio-container{background:#1c1714;}
#hdr h1{font-family:Georgia,serif;color:#f4d9a0;}
.feed{font-family:Georgia,serif;font-size:1.02rem;line-height:1.6;
      background:#2a2118;border-radius:12px;padding:16px 20px;color:#efe3cf;max-height:560px;overflow:auto;}
.feed .ev{color:#d98c4a;font-style:italic;}
.feed .av{font-size:1.15rem;margin-right:3px;}
"""

def _build_portraits():
    css, cls = [], {}
    pdir = os.path.join(os.path.dirname(os.path.abspath(__file__)), "portraits")
    for name, key in town.PORTRAIT.items():
        p = os.path.join(pdir, key + ".png")
        if os.path.exists(p):
            im = Image.open(p).convert("RGB").resize((88, 88))
            buf = io.BytesIO()
            im.save(buf, format="JPEG", quality=82)
            b64 = base64.b64encode(buf.getvalue()).decode()
            css.append(f".pav-{key}{{background-image:url(data:image/jpeg;base64,{b64})}}")
            cls[name] = key
    return "\n".join(css), cls

PORTRAIT_CSS, PORTRAIT_CLS = _build_portraits()
CSS += ("\n.pav{display:inline-block;width:34px;height:34px;border-radius:50%;"
        "background-size:cover;background-position:center top;vertical-align:middle;"
        "margin-right:8px;border:1px soli ...

[Assistant] {"matches":[{"quest":"Thousand Token Wood","confidence":0.95,"evidence":"town of tiny AI minds gossiping, feuding, falling in love","source":"readme"},{"quest":"Off the Grid","confidence":0.93,"evidence":"No cloud APIs. No giant model. Every mind runs locally","source":"readme"},{"quest":"Off-Brand","confidence":0.85,"evidence":".gradio-container{background:#1c1714;} custom .feed CSS","source":"app_file"},{"quest":"Best Agent","confidence":0.5,"evidence":"Each is its own small-model agent that improvises","source":"readme"}]}


Llama Champion
Off the Grid
Off-Brand
Thousand Token Wood

[System] You classify hackathon projects against fixed quest dimensions. Return exactly one strict JSON object and nothing else. The first character must be { and the last character must be }. Each match needs quest, confidence, evidence, and source (readme or app_file). Never emit markdown, prose, a top-level array, extra keys, or an unknown or rephrased quest name.

[User]
Classify this hackathon project against the quest dimensions below.
Read the two evidence segments (README and APP_FILE) and judge each quest only from them.

Quests (copy the id on the left verbatim):
- Off the Grid: Runs the model on-device with no remote inference call: weights load locally and inference happens in-process, not over a hosted API. Signals: AWARD on a local in-process load: from_pretrained / pipeline / llama_cpp / diffusers / vLLM / ONNX, GGUF weights, @spaces.GPU. DISQUALIFY (do NOT award) on ANY remote inference call, even via huggingface_hub: InferenceClient, HF Inference API/Endpoints, gradio_client to a remote Space, replicate/together/openrouter/fal/groq, a *.modal.run or other HTTP inference endpoint, or openai/anthropic/gemini/cohere clients. A remote call disqualifies regardless of which model it names.
- Well-Tuned: Uses or publishes a fine-tuned or LoRA-adapted model rather than only stock checkpoints. Signals: LoRA/PEFT adapter, fine-tuned model repo, training script, words like fine-tune, adapter, SFT, distilled.
- Off-Brand: Ships a custom interface beyond default Gradio styling, with a memorable look or voice. Signals: custom CSS/HTML/JS, gr.HTML, gr.Blocks theme/css=, gr.Server, custom components, bespoke theming.
- Llama Champion: Runs a model through the llama.cpp runtime. Signals: llama-cpp-python, from llama_cpp import Llama, GGUF file, llama.cpp, Llama( constructor.
- Sharing is Caring: Produces an output people can save, post, or compare, or publishes an agent trace to the Hub. Signals: download/export button, gr.File/gr.DownloadButton, save PNG/PDF/JSON, push_to_hub of a trace or dataset.
- Field Notes: Documents the build itself with notes, a write-up, or a blog/report link. Signals: README has a substantial build write-up, devlog, lessons learned, or a blog/report/Notion link.
- Backyard AI: Solves a concrete real-world problem for a specific, named person or persona. Signals: README frames a real user and task (caregiving, a relative, a job, a household chore), practical utility.
- Thousand Token Wood: A delightful, playful, or artistic experience that would not exist without AI. Signals: story/game/art/whimsy framing, generative characters or worlds, playful tone, creative novelty.
- OpenBMB: Uses a model published by OpenBMB (the openbmb org), such as the MiniCPM family. Signals: The model id org prefix must be exactly openbmb/ (openbmb/MiniCPM*, OpenCPM). A model from any other org is NOT OpenBMB: openai/gpt-oss, Qwen/..., meta-llama/..., google/..., nvidia/..., microsoft/..., mistralai/... do NOT count just because a model id is present.
- Nemotron: Uses an NVIDIA Nemotron model (Nemotron LLM, Parakeet, Nemotron-Speech, Canary). Signals: model repo nvidia/...nemotron..., Parakeet, nemotron-speech, Canary ASR.
- Modal: Uses Modal for training, inference, or background compute. Signals: import modal, modal.App, @app.function, Modal endpoint/volume, README cites Modal compute.
- Tiny Titan: Runs on a genuinely small model of about four billion parameters or fewer. Signals: AWARD when the model name says <=4B: 0.5B/1B/1.5B/2B/3B/4B or tiny/small/nano/mini (Qwen2.5-1.5B, MiniCPM5-1B, gemma-2b). Do NOT award for 7B/8B/12B/13B/20B/27B/35B+ models (e.g. gpt-oss-20b, Qwen2.5-7B); a version number like V-4.6 is not a parameter count.
- Best Agent: An agentic build: tool use, function calling, planning, or an autonomous multi-step loop. Signals: tool/function calling, an agent/planner loop, multiple orchestrated tools, ReAct, multi-step reasoning over tools.

Rules:
- Include a quest only when a segment gives clear, specific evidence.
- quest must be one id from the list above, copied exactly. Never invent or rephrase a quest name.
- confidence is a number between 0 and 1.
- evidence is a 3-to-12 word quote or tight paraphrase taken from the segment you cite.
- source is "readme" when the evidence is in the README segment, "app_file" when it is in the APP_FILE segment.
- At most one match per quest. Sort matches by confidence, highest first.
- If no quest has clear evidence, return an empty matches list.
- Output exactly one JSON object: {"matches":[{"quest":"...","confidence":0.0,"evidence":"...","source":"readme"}]}.
- No markdown, no code fences, no commentary, no extra keys.

METADATA: {"title": "Oneiros", "sdk": "gradio", "declared_models": [], "tags": ["gradio", "region:us"]}

[README]
# ✦ ONEIROS **Your dreams, mapped with a small model you control — not sent to ChatGPT.** Oneiros mengubah catatan mimpi menjadi **peta SVG** plus panel ringkasan entitas, menggunakan **Qwen2.5-7B-Instruct** (GGUF) via **llama-cpp-python** — tanpa API LLM pihak ketiga. Proyek ini dibuat untuk [Build Small Hackathon](https://huggingface.co/build-small-hackathon) (Gradio × Hugging Face), track **An Adventure in Thousand Token Wood**. --- ## Status repositori (Day 1) | Komponen | Status | |----------|--------| | `model/` loader + extractor + normalisasi | ✅ Day 1 | | `app.py` minimal (mimpi → JSON) | ✅ Day 1 | | `storage/trace_logger.py` | ✅ Day 1 | | `tests/test_extractor.py` | ✅ (butuh GGUF lokal) | | Peta SVG (`map/`) | 🔲 Day 2 | --- ## Deploy HF Space **Space resmi:** https://huggingface.co/spaces/build-small-hackathon/oneiros 1. Sebelum push: `./scripts/prepare_space_requirements.sh` (salin wheel Linux ke `requirements.txt`). 2. Push ke org `build-small-hackathon/oneiros`. 3. **Variables** (Settings): `N_GPU_LAYERS=0`, `N_CTX=4096`; `ONEIROS_SKIP_WARMUP=1` sampai preload selesai. 4. Preload 2 shard Q4_K_M (~15–45 menit). Cek log: `[oneiros] diagnosis` → `shard_pair_ok: True`. 5. Setelah Running: uji 1 mimpi di UI. Detail: [docs/08-deploy-hf-space.md](docs/08-deploy-hf-space.md) · Checklist Day 2: [docs/16-checklist-sebelum-day2.md](docs/16-checklist-sebelum-day2.md). --- ## Quick start (lokal) **Pakai `requirements-local.txt`** — jangan `requirements.txt` (itu untuk Space L ...

[APP_FILE] app.py
from __future__ import annotations
from map.format_panel import format_panel_entitas
from map.generator import generate_dream_map
from ui.gaya_oneiros import (
from ui.konstan import PANJANG_MINIMUM_MIMPI
from model.loader import (
from model.extractor import extract_entities_dengan_waktu
from storage.trace_logger import log_trace

""" # build: 20260603-1016
Oneiros — Day 2: mimpi → SVG dream map + Markdown panel (Space & lokal).
HF Spaces: objek `demo` harus ada di level modul (bukan hanya di __main__).
"""
from __future__ import annotations

import os
import traceback

import gradio as gr

from map.format_panel import format_panel_entitas
from map.generator import generate_dream_map
from ui.gaya_oneiros import (
    CONTOH_MIMPI,
    CSS_ONEIROS,
    PESAN_STATUS_IDLE,
    TEKS_FOOTER,
    TEKS_LANGKAH,
    buat_teks_header,
    buat_teks_latar,
    format_status_error,
    format_status_hasil,
    tema_oneiros,
)
from ui.konstan import PANJANG_MINIMUM_MIMPI

DISCLAIMER = (
    "This online demo reads your dream on our servers so you can try it in the browser. "
    "Want to keep dreams only on your own computer? See the project README."
)

def _pastikan_llama_cpp() -> bool:
    """Install llama-cpp-python jika tidak ada di Docker image (fallback runtime)."""
    try:
        import llama_cpp  # noqa: F401
        return True
    except ImportError:
        pass

    if not os.getenv("SPACE_ID"):
        return False  # lokal: jangan install otomatis

    print("[oneiros] llama_cpp tidak ada — install runtime (1-3 menit)…")
    import subprocess

    wheel = (
        "llama-cpp-python @ https://github.com/abetlen/llama-cpp-python"
        "/releases/download/v0.3.19/llama_cpp_python-0.3.19-cp310-cp310-linux_x86_64.whl"
    )
    result = subprocess.run(
        ["pip", "install", "--no-cache-dir", "--quiet", wheel],
        capture_output=True,
        text=True, ...

[Assistant] {"matches":[{"quest":"Llama Champion","confidence":0.96,"evidence":"Qwen2.5-7B-Instruct (GGUF) via llama-cpp-python","source":"readme"},{"quest":"Off the Grid","confidence":0.91,"evidence":"tanpa API LLM pihak ketiga (no third-party LLM API)","source":"readme"},{"quest":"Off-Brand","confidence":0.84,"evidence":"imports CSS_ONEIROS and tema_oneiros (custom theme)","source":"app_file"},{"quest":"Thousand Token Wood","confidence":0.82,"evidence":"track An Adventure in Thousand Token Wood; dreams to SVG","source":"readme"}]}


Off the Grid
Off-Brand
Thousand Token Wood
Well-Tuned

[System] You classify hackathon projects against fixed quest dimensions. Return exactly one strict JSON object and nothing else. The first character must be { and the last character must be }. Each match needs quest, confidence, evidence, and source (readme or app_file). Never emit markdown, prose, a top-level array, extra keys, or an unknown or rephrased quest name.

[User]
Classify this hackathon project against the quest dimensions below.
Read the two evidence segments (README and APP_FILE) and judge each quest only from them.

Quests (copy the id on the left verbatim):
- Off the Grid: Runs the model on-device with no remote inference call: weights load locally and inference happens in-process, not over a hosted API. Signals: AWARD on a local in-process load: from_pretrained / pipeline / llama_cpp / diffusers / vLLM / ONNX, GGUF weights, @spaces.GPU. DISQUALIFY (do NOT award) on ANY remote inference call, even via huggingface_hub: InferenceClient, HF Inference API/Endpoints, gradio_client to a remote Space, replicate/together/openrouter/fal/groq, a *.modal.run or other HTTP inference endpoint, or openai/anthropic/gemini/cohere clients. A remote call disqualifies regardless of which model it names.
- Well-Tuned: Uses or publishes a fine-tuned or LoRA-adapted model rather than only stock checkpoints. Signals: LoRA/PEFT adapter, fine-tuned model repo, training script, words like fine-tune, adapter, SFT, distilled.
- Off-Brand: Ships a custom interface beyond default Gradio styling, with a memorable look or voice. Signals: custom CSS/HTML/JS, gr.HTML, gr.Blocks theme/css=, gr.Server, custom components, bespoke theming.
- Llama Champion: Runs a model through the llama.cpp runtime. Signals: llama-cpp-python, from llama_cpp import Llama, GGUF file, llama.cpp, Llama( constructor.
- Sharing is Caring: Produces an output people can save, post, or compare, or publishes an agent trace to the Hub. Signals: download/export button, gr.File/gr.DownloadButton, save PNG/PDF/JSON, push_to_hub of a trace or dataset.
- Field Notes: Documents the build itself with notes, a write-up, or a blog/report link. Signals: README has a substantial build write-up, devlog, lessons learned, or a blog/report/Notion link.
- Backyard AI: Solves a concrete real-world problem for a specific, named person or persona. Signals: README frames a real user and task (caregiving, a relative, a job, a household chore), practical utility.
- Thousand Token Wood: A delightful, playful, or artistic experience that would not exist without AI. Signals: story/game/art/whimsy framing, generative characters or worlds, playful tone, creative novelty.
- OpenBMB: Uses a model published by OpenBMB (the openbmb org), such as the MiniCPM family. Signals: The model id org prefix must be exactly openbmb/ (openbmb/MiniCPM*, OpenCPM). A model from any other org is NOT OpenBMB: openai/gpt-oss, Qwen/..., meta-llama/..., google/..., nvidia/..., microsoft/..., mistralai/... do NOT count just because a model id is present.
- Nemotron: Uses an NVIDIA Nemotron model (Nemotron LLM, Parakeet, Nemotron-Speech, Canary). Signals: model repo nvidia/...nemotron..., Parakeet, nemotron-speech, Canary ASR.
- Modal: Uses Modal for training, inference, or background compute. Signals: import modal, modal.App, @app.function, Modal endpoint/volume, README cites Modal compute.
- Tiny Titan: Runs on a genuinely small model of about four billion parameters or fewer. Signals: AWARD when the model name says <=4B: 0.5B/1B/1.5B/2B/3B/4B or tiny/small/nano/mini (Qwen2.5-1.5B, MiniCPM5-1B, gemma-2b). Do NOT award for 7B/8B/12B/13B/20B/27B/35B+ models (e.g. gpt-oss-20b, Qwen2.5-7B); a version number like V-4.6 is not a parameter count.
- Best Agent: An agentic build: tool use, function calling, planning, or an autonomous multi-step loop. Signals: tool/function calling, an agent/planner loop, multiple orchestrated tools, ReAct, multi-step reasoning over tools.

Rules:
- Include a quest only when a segment gives clear, specific evidence.
- quest must be one id from the list above, copied exactly. Never invent or rephrase a quest name.
- confidence is a number between 0 and 1.
- evidence is a 3-to-12 word quote or tight paraphrase taken from the segment you cite.
- source is "readme" when the evidence is in the README segment, "app_file" when it is in the APP_FILE segment.
- At most one match per quest. Sort matches by confidence, highest first.
- If no quest has clear evidence, return an empty matches list.
- Output exactly one JSON object: {"matches":[{"quest":"...","confidence":0.0,"evidence":"...","source":"readme"}]}.
- No markdown, no code fences, no commentary, no extra keys.

METADATA: {"title": "Oracle Ternary Flame", "sdk": "gradio", "declared_models": [], "tags": ["gradio", "region:us"]}

[README]
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference

[APP_FILE] app.py
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from peft import PeftModel
from huggingface_hub import snapshot_download

import gradio as gr
import torch
import spaces
from transformers import AutoTokenizer, AutoModelForCausalLM, BitsAndBytesConfig
from peft import PeftModel

# ── Config ────────────────────────────────────────────────────────────────────
BASE_MODEL_ID = "google/gemma-4-12b-it"
LORA_MODEL_ID = "keypa/oracle-gemma4-12b-lora"
SYSTEM_PROMPT = (
    "You are the Oracle of the Ternary Flame. "
    "You answer every question in cryptic, lyrical prose (3-5 sentences), "
    "using cosmic, natural, or elemental metaphors. "
    "The real answer is encoded implicitly — never state it directly. "
    "You never break character."
)

# ── Pre-download weights at startup (CPU, no GPU needed) ─────────────────────
from huggingface_hub import snapshot_download
import os

print("Pre-downloading base model weights...")
base_model_path = snapshot_download(
    repo_id=BASE_MODEL_ID,
    ignore_patterns=["*.msgpack", "*.h5", "flax_model*"],
)
print(f"Base model cached at: {base_model_path}")

lora_model_path = snapshot_download(repo_id=LORA_MODEL_ID)
print(f"LoRA adapter cached at: {lora_model_path}")

# ── Model loading (lazy, inside GPU context) ──────────────────────────────────
model = None
tokenizer = None

def load_model():
    global model, tokenizer
    if model is not None:
        return

    bnb_config = BitsAndBytesConfig(
        load_in_4bit=True,
        bnb_4bit_quant_type="nf4",
        bnb_4bit_compute_dtype=torch.float16,
        bnb_4bit_use_double_quant=True,
    )
    tokenizer = AutoTokenizer.from_pretrained(lora_model_path)
    base = AutoModelForCausalLM.from_pretrained(
        base_model_path,
        quantization_config=bnb_config,
        device_map={"": "cuda:0"},
        low_cpu_mem_usage=True,
    )
    m ...

[Assistant] {"matches":[{"quest":"Well-Tuned","confidence":0.97,"evidence":"PeftModel.from_pretrained loads keypa/oracle-gemma4-12b-lora adapter","source":"app_file"},{"quest":"Off-Brand","confidence":0.95,"evidence":"large bespoke CSS, gr.HTML headers, demo.launch(css=CSS)","source":"app_file"},{"quest":"Thousand Token Wood","confidence":0.85,"evidence":"Oracle of the Ternary Flame, cryptic cosmic prose, never break character","source":"app_file"},{"quest":"Off the Grid","confidence":0.7,"evidence":"local transformers + peft load, no proprietary cloud API imports","source":"app_file"}]}


[System] You classify hackathon projects against fixed quest dimensions. Return exactly one strict JSON object and nothing else. The first character must be { and the last character must be }. Each match needs quest, confidence, evidence, and source (readme or app_file). Never emit markdown, prose, a top-level array, extra keys, or an unknown or rephrased quest name.

[User]
Classify this hackathon project against the quest dimensions below.
Read the two evidence segments (README and APP_FILE) and judge each quest only from them.

Quests (copy the id on the left verbatim):
- Off the Grid: Runs the model on-device with no remote inference call: weights load locally and inference happens in-process, not over a hosted API. Signals: AWARD on a local in-process load: from_pretrained / pipeline / llama_cpp / diffusers / vLLM / ONNX, GGUF weights, @spaces.GPU. DISQUALIFY (do NOT award) on ANY remote inference call, even via huggingface_hub: InferenceClient, HF Inference API/Endpoints, gradio_client to a remote Space, replicate/together/openrouter/fal/groq, a *.modal.run or other HTTP inference endpoint, or openai/anthropic/gemini/cohere clients. A remote call disqualifies regardless of which model it names.
- Well-Tuned: Uses or publishes a fine-tuned or LoRA-adapted model rather than only stock checkpoints. Signals: LoRA/PEFT adapter, fine-tuned model repo, training script, words like fine-tune, adapter, SFT, distilled.
- Off-Brand: Ships a custom interface beyond default Gradio styling, with a memorable look or voice. Signals: custom CSS/HTML/JS, gr.HTML, gr.Blocks theme/css=, gr.Server, custom components, bespoke theming.
- Llama Champion: Runs a model through the llama.cpp runtime. Signals: llama-cpp-python, from llama_cpp import Llama, GGUF file, llama.cpp, Llama( constructor.
- Sharing is Caring: Produces an output people can save, post, or compare, or publishes an agent trace to the Hub. Signals: download/export button, gr.File/gr.DownloadButton, save PNG/PDF/JSON, push_to_hub of a trace or dataset.
- Field Notes: Documents the build itself with notes, a write-up, or a blog/report link. Signals: README has a substantial build write-up, devlog, lessons learned, or a blog/report/Notion link.
- Backyard AI: Solves a concrete real-world problem for a specific, named person or persona. Signals: README frames a real user and task (caregiving, a relative, a job, a household chore), practical utility.
- Thousand Token Wood: A delightful, playful, or artistic experience that would not exist without AI. Signals: story/game/art/whimsy framing, generative characters or worlds, playful tone, creative novelty.
- OpenBMB: Uses a model published by OpenBMB (the openbmb org), such as the MiniCPM family. Signals: The model id org prefix must be exactly openbmb/ (openbmb/MiniCPM*, OpenCPM). A model from any other org is NOT OpenBMB: openai/gpt-oss, Qwen/..., meta-llama/..., google/..., nvidia/..., microsoft/..., mistralai/... do NOT count just because a model id is present.
- Nemotron: Uses an NVIDIA Nemotron model (Nemotron LLM, Parakeet, Nemotron-Speech, Canary). Signals: model repo nvidia/...nemotron..., Parakeet, nemotron-speech, Canary ASR.
- Modal: Uses Modal for training, inference, or background compute. Signals: import modal, modal.App, @app.function, Modal endpoint/volume, README cites Modal compute.
- Tiny Titan: Runs on a genuinely small model of about four billion parameters or fewer. Signals: AWARD when the model name says <=4B: 0.5B/1B/1.5B/2B/3B/4B or tiny/small/nano/mini (Qwen2.5-1.5B, MiniCPM5-1B, gemma-2b). Do NOT award for 7B/8B/12B/13B/20B/27B/35B+ models (e.g. gpt-oss-20b, Qwen2.5-7B); a version number like V-4.6 is not a parameter count.
- Best Agent: An agentic build: tool use, function calling, planning, or an autonomous multi-step loop. Signals: tool/function calling, an agent/planner loop, multiple orchestrated tools, ReAct, multi-step reasoning over tools.

Rules:
- Include a quest only when a segment gives clear, specific evidence.
- quest must be one id from the list above, copied exactly. Never invent or rephrase a quest name.
- confidence is a number between 0 and 1.
- evidence is a 3-to-12 word quote or tight paraphrase taken from the segment you cite.
- source is "readme" when the evidence is in the README segment, "app_file" when it is in the APP_FILE segment.
- At most one match per quest. Sort matches by confidence, highest first.
- If no quest has clear evidence, return an empty matches list.
- Output exactly one JSON object: {"matches":[{"quest":"...","confidence":0.0,"evidence":"...","source":"readme"}]}.
- No markdown, no code fences, no commentary, no extra keys.

METADATA: {"title": "Retail Insight AI Pro", "sdk": "gradio", "declared_models": [], "tags": ["gradio", "region:us"]}

[README]
# 🛒 Retail-Insight-AI v2.5 ### ⚡ Build Small Hackathon Submission (Backyard AI Track) Retail-Insight-AI ek privacy-first, 100% offline edge analytics dashboard hai jo local shopkeepers ko enterprise-level operational insights deta hai bina unka data cloud par leak kiye. ### ✨ Key Features - **Instant 10K Row Audit:** Sirf 2 seconds mein pure sales log ko process karta hai. - **Semantic Mapping:** Intelligent column mapping automatic Product Names aur Revenue attributes ko detect karti hai. - **Edge Heuristics:** Zero cloud API dependencies, complete privacy for local stores. ## 📺 Live Video Demo [Watch the Demo Video Here](https://www.instagram.com/reel/DZNAcHlv72c/?utm_source=ig_web_copy_link&igsh=MzRlODBiNWFlZA==)

[APP_FILE] app.py
import sys
import types

# 🚨 DYNAMIC FIX 1: Python 3.13 Compatibility Audio Patch
if 'audioop' not in sys.modules:
    dummy_audioop = types.ModuleType('audioop')
    dummy_audioop.error = Exception
    sys.modules['audioop'] = dummy_audioop

if 'pyaudioop' not in sys.modules:
    dummy_pyaudioop = types.ModuleType('pyaudioop')
    dummy_pyaudioop.error = Exception
    sys.modules['pyaudioop'] = dummy_pyaudioop

# 🚨 DYNAMIC FIX 2: Critical HuggingFace Hub 'HfFolder' Import Patch
try:
    import huggingface_hub
except ImportError:
    huggingface_hub = types.ModuleType('huggingface_hub')
    sys.modules['huggingface_hub'] = huggingface_hub

if not hasattr(huggingface_hub, 'HfFolder'):
    class DummyHfFolder:
        @staticmethod
        def get_token(): return None
        @staticmethod
        def save_token(token): pass
        @staticmethod
        def delete_token(): pass
    huggingface_hub.HfFolder = DummyHfFolder

import gradio as gr
import pandas as pd
import os

def generate_local_insights(summary_data):
    insights = []
    if 'top_product' in summary_data:
        insights.append(f"🔥 **Inventory Focus:** Your star performer is **{summary_data['top_product']}**. Consider running targeted local ads or bundling weaker products with it to clear old stock.")
    if 'low_stock' in summary_data and summary_data['low_stock']:
        items = ", ".join([str(i).title() for i in summary_data['low_stock']])
        insights.append(f"🚨 **Supply Chain Alert:** Restock emergency! **{items}** are dropping below critical levels. Reorder immediately to avoid missing out on sales volume.")
    else:
        insights.append("✅ **Stock Status:** Inventory levels are healthy across detected lines. Keep monitoring expiration or seasonal dips.")
    if 'total_revenue' in summary_data:
        insights.append(f"📈 **Revenue Milestone:** Total processed volume stands at **{summary_ ...

[Assistant] {"matches":[{"quest":"Backyard AI","confidence":0.7,"evidence":"local shopkeepers ko enterprise-level operational insights deta hai","source":"readme"}]}


Backyard AI
Off the Grid
Tiny Titan
Well-Tuned

[System] You classify hackathon projects against fixed quest dimensions. Return exactly one strict JSON object and nothing else. The first character must be { and the last character must be }. Each match needs quest, confidence, evidence, and source (readme or app_file). Never emit markdown, prose, a top-level array, extra keys, or an unknown or rephrased quest name.

[User]
Classify this hackathon project against the quest dimensions below.
Read the two evidence segments (README and APP_FILE) and judge each quest only from them.

Quests (copy the id on the left verbatim):
- Off the Grid: Runs the model on-device with no remote inference call: weights load locally and inference happens in-process, not over a hosted API. Signals: AWARD on a local in-process load: from_pretrained / pipeline / llama_cpp / diffusers / vLLM / ONNX, GGUF weights, @spaces.GPU. DISQUALIFY (do NOT award) on ANY remote inference call, even via huggingface_hub: InferenceClient, HF Inference API/Endpoints, gradio_client to a remote Space, replicate/together/openrouter/fal/groq, a *.modal.run or other HTTP inference endpoint, or openai/anthropic/gemini/cohere clients. A remote call disqualifies regardless of which model it names.
- Well-Tuned: Uses or publishes a fine-tuned or LoRA-adapted model rather than only stock checkpoints. Signals: LoRA/PEFT adapter, fine-tuned model repo, training script, words like fine-tune, adapter, SFT, distilled.
- Off-Brand: Ships a custom interface beyond default Gradio styling, with a memorable look or voice. Signals: custom CSS/HTML/JS, gr.HTML, gr.Blocks theme/css=, gr.Server, custom components, bespoke theming.
- Llama Champion: Runs a model through the llama.cpp runtime. Signals: llama-cpp-python, from llama_cpp import Llama, GGUF file, llama.cpp, Llama( constructor.
- Sharing is Caring: Produces an output people can save, post, or compare, or publishes an agent trace to the Hub. Signals: download/export button, gr.File/gr.DownloadButton, save PNG/PDF/JSON, push_to_hub of a trace or dataset.
- Field Notes: Documents the build itself with notes, a write-up, or a blog/report link. Signals: README has a substantial build write-up, devlog, lessons learned, or a blog/report/Notion link.
- Backyard AI: Solves a concrete real-world problem for a specific, named person or persona. Signals: README frames a real user and task (caregiving, a relative, a job, a household chore), practical utility.
- Thousand Token Wood: A delightful, playful, or artistic experience that would not exist without AI. Signals: story/game/art/whimsy framing, generative characters or worlds, playful tone, creative novelty.
- OpenBMB: Uses a model published by OpenBMB (the openbmb org), such as the MiniCPM family. Signals: The model id org prefix must be exactly openbmb/ (openbmb/MiniCPM*, OpenCPM). A model from any other org is NOT OpenBMB: openai/gpt-oss, Qwen/..., meta-llama/..., google/..., nvidia/..., microsoft/..., mistralai/... do NOT count just because a model id is present.
- Nemotron: Uses an NVIDIA Nemotron model (Nemotron LLM, Parakeet, Nemotron-Speech, Canary). Signals: model repo nvidia/...nemotron..., Parakeet, nemotron-speech, Canary ASR.
- Modal: Uses Modal for training, inference, or background compute. Signals: import modal, modal.App, @app.function, Modal endpoint/volume, README cites Modal compute.
- Tiny Titan: Runs on a genuinely small model of about four billion parameters or fewer. Signals: AWARD when the model name says <=4B: 0.5B/1B/1.5B/2B/3B/4B or tiny/small/nano/mini (Qwen2.5-1.5B, MiniCPM5-1B, gemma-2b). Do NOT award for 7B/8B/12B/13B/20B/27B/35B+ models (e.g. gpt-oss-20b, Qwen2.5-7B); a version number like V-4.6 is not a parameter count.
- Best Agent: An agentic build: tool use, function calling, planning, or an autonomous multi-step loop. Signals: tool/function calling, an agent/planner loop, multiple orchestrated tools, ReAct, multi-step reasoning over tools.

Rules:
- Include a quest only when a segment gives clear, specific evidence.
- quest must be one id from the list above, copied exactly. Never invent or rephrase a quest name.
- confidence is a number between 0 and 1.
- evidence is a 3-to-12 word quote or tight paraphrase taken from the segment you cite.
- source is "readme" when the evidence is in the README segment, "app_file" when it is in the APP_FILE segment.
- At most one match per quest. Sort matches by confidence, highest first.
- If no quest has clear evidence, return an empty matches list.
- Output exactly one JSON object: {"matches":[{"quest":"...","confidence":0.0,"evidence":"...","source":"readme"}]}.
- No markdown, no code fences, no commentary, no extra keys.

METADATA: {"title": "Adwuma Pa ASR Eval", "sdk": "gradio", "declared_models": [], "tags": ["gradio", "region:us"]}

[README]
# Adwuma Pa ASR Eval This Space is the first build step for Adwuma Pa. It tests small ASR models on real Twi, Fante, and Ghanaian English family recordings before choosing the production voice path. Community testers can vote for the model that best preserves the meaning of each sample. Rough WER is only shown when exact reference text is provided, so votes are useful when people can judge the transcript by ear. ## Models - `facebook/mms-1b-all`: primary recommendation for Twi and Fante coverage. - `teckedd/whisper_small-waxal_akan-asr-v1`: published Akan fine-tune for the Well-Tuned badge. - `GiftMark/akan-whisper-model`: community Akan fallback. ## Test Protocol 1. Record 5 to 10 natural samples from the intended family users. 2. Test Twi first, then Fante, then Ghanaian English. 3. Add the reference text when possible to compare rough WER. 4. Choose the model that best captures concern signals, not perfect spelling. 5. Keep text fallback in the main app for low-confidence or garbled output. ## Voting After comparing outputs, pick the model that best captured the care signal. Add a short note such as "caught walking pain" or "missed the isolation phrase." These votes help decide whether the next step should be fine-tuning.

[APP_FILE] app.py
from __future__ import annotations
from collections import Counter
from datetime import datetime, timezone
from functools import lru_cache
from pathlib import Path
from typing import Any
from transformers import AutoProcessor, Wav2Vec2ForCTC
from transformers import WhisperForConditionalGeneration, WhisperProcessor

from __future__ import annotations

import json
from collections import Counter
from datetime import datetime, timezone
from functools import lru_cache
from pathlib import Path
from typing import Any

import gradio as gr
import numpy as np

MODEL_REGISTRY = {
    "MMS-1B-all (recommended)": {
        "model_id": "facebook/mms-1b-all",
        "type": "mms",
        "parameter_count": "1B",
        "notes": "Native multilingual ASR with Twi target language and Fante/Akan coverage.",
    },
    "Adwuma Pa Akan Whisper fine-tune": {
        "model_id": "teckedd/whisper_small-waxal_akan-asr-v1",
        "type": "whisper",
        "parameter_count": "0.2B",
        "notes": "Published Akan fine-tune; useful for Well-Tuned badge validation.",
    },
    "GiftMark Akan Whisper": {
        "model_id": "GiftMark/akan-whisper-model",
        "type": "whisper",
        "parameter_count": "0.2B",
        "notes": "Community Akan fallback, Twi-oriented.",
    },
}

LANGUAGE_CODES = {
    "Twi": "aka",
    "Fante": "aka",
    "Ghanaian English": "eng",
}

VOTES_PATH = Path("community_votes.jsonl")

@lru_cache(maxsize=4)
def load_model(model_name: str) -> tuple[Any, Any, str]:
    cfg = MODEL_REGISTRY[model_name]
    if cfg["type"] == "mms":
        from transformers import AutoProcessor, Wav2Vec2ForCTC

        processor = AutoProcessor.from_pretrained(cfg["model_id"])
        model = Wav2Vec2ForCTC.from_pretrained(cfg["model_id"])
        return processor, model, "mms"

    from transformers import WhisperForConditionalGeneration, WhisperProcessor

    processor = Whi ...

[Assistant] {"matches":[{"quest":"Tiny Titan","confidence":0.92,"evidence":"parameter_count 1B and 0.2B, all small models","source":"app_file"},{"quest":"Well-Tuned","confidence":0.88,"evidence":"published Akan fine-tune for the Well-Tuned badge","source":"readme"},{"quest":"Off the Grid","confidence":0.83,"evidence":"transformers AutoProcessor/Wav2Vec2ForCTC loaded locally, no cloud API","source":"app_file"},{"quest":"Backyard AI","confidence":0.8,"evidence":"tests real Twi, Fante, Ghanaian English family recordings","source":"readme"}]}