bash98 commited on
Commit
0f85049
·
verified ·
1 Parent(s): a43117e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +76 -76
app.py CHANGED
@@ -1,96 +1,96 @@
1
- """Document Q&A with Manual RAG - CPU inference on a ZeroGPU Space.
2
 
3
- The two visible actions stay on CPU. A hidden, registered GPU handler
4
- is present solely to satisfy ZeroGPU startup validation.
 
5
  """
6
 
7
- import spaces # Import before Gradio, torch, or Hugging Face model libraries.
 
8
 
9
  import os
10
  import traceback
11
 
12
- # Do NOT set CUDA_VISIBLE_DEVICES on ZeroGPU hardware.
13
  os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
14
 
15
  import gradio as gr
 
 
 
 
 
16
 
17
- from rag_core import answer_question, display_evidence, load_retriever
18
 
 
 
 
 
 
 
19
 
20
- @spaces.GPU(duration=10)
21
- def zerogpu_registration():
22
- """Registered but intentionally unused ZeroGPU handler.
 
 
23
 
24
- The host requires at least one @spaces.GPU decorated Gradio event
25
- on a ZeroGPU Space. Users do not click this handler, and the two
26
- visible buttons do all work on CPU.
27
- """
28
- return "ZeroGPU registration handler (unused)."
29
 
 
 
 
30
 
 
 
 
 
 
31
 
32
- CUSTOM_CSS = """
33
- .gradio-container {
34
- max-width: 1080px !important;
35
- margin: 0 auto !important;
36
- padding: 22px 16px 38px !important;
37
- }
 
 
 
 
38
 
39
- #rag-hero {
40
- padding: 26px 30px;
41
- border: 1px solid var(--border-color-primary);
42
- border-radius: 20px;
43
- background: linear-gradient(
44
- 125deg,
45
- color-mix(in srgb, var(--primary-500) 13%, var(--block-background-fill)) 0%,
46
- var(--block-background-fill) 75%
47
- );
48
- margin-bottom: 18px;
49
- }
50
- #rag-hero .eyebrow {
51
- font-size: 0.76rem;
52
- text-transform: uppercase;
53
- font-weight: 750;
54
- letter-spacing: 0.11em;
55
- color: var(--primary-500);
56
- margin-bottom: 9px;
57
- }
58
- #rag-hero h1 {
59
- font-size: clamp(1.65rem, 3vw, 2.35rem);
60
- font-weight: 760;
61
- line-height: 1.17;
62
- letter-spacing: -0.035em;
63
- margin: 0 0 10px;
64
- }
65
- #rag-hero p {
66
- color: var(--body-text-color-subdued);
67
- font-size: 0.99rem;
68
- max-width: 750px;
69
- line-height: 1.6;
70
- margin: 0;
71
- }
72
- #rag-hero .meta {
73
- font-size: 0.82rem;
74
- color: var(--body-text-color-subdued);
75
- margin-top: 15px;
76
- }
77
- #rag-input textarea { font-size: 1.03rem !important; }
78
- #rag-actions button { min-height: 48px !important; font-weight: 650; }
79
- #rag-status { margin: 4px 0 8px; }
80
- #rag-status p { font-size: 0.9rem; color: var(--body-text-color-subdued); }
81
- #rag-result-heading h3 { font-size: 1.13rem; margin: 12px 0 0; }
82
- #rag-answer textarea { font-size: 1.04rem !important; line-height: 1.6 !important; }
83
- #rag-evidence textarea { font-size: 0.94rem !important; line-height: 1.55 !important; }
84
- #rag-footnote p { font-size: 0.82rem; color: var(--body-text-color-subdued); }
85
- @media (max-width: 680px) {
86
- #rag-hero { padding: 20px 18px; border-radius: 16px; }
87
- .gradio-container { padding: 12px 10px 22px !important; }
88
- }
89
- """
90
 
 
 
91
 
92
- def format_result(result):
93
- """Return answer, complete source evidence, and a simple status line."""
94
- answer = result.get("answer", "")
95
- evidence = display_evidence(result)
96
- hits = result.get("retrieved") or []
 
1
+ """Document Q&A with Manual RAG.
2
 
3
+ Single-file version for Hugging Face ZeroGPU hardware with CPU inference.
4
+ The two visible actions use CPU only. A disabled, hidden GPU event is
5
+ registered because the ZeroGPU hardware runtime requires one.
6
  """
7
 
8
+ # Hugging Face ZeroGPU requires 'spaces' to load before ML libraries.
9
+ import spaces
10
 
11
  import os
12
  import traceback
13
 
 
14
  os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
15
 
16
  import gradio as gr
17
+ import numpy as np
18
+ import torch
19
+ from datasets import load_dataset
20
+ from sentence_transformers import SentenceTransformer
21
+ from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
22
 
 
23
 
24
+ EMBEDDING_MODEL = "sentence-transformers/all-MiniLM-L6-v2"
25
+ GENERATION_MODEL = "google/flan-t5-small"
26
+ DATASET_ID = "rajpurkar/squad"
27
+ DATASET_REVISION = "7b6d24c440a36b6815f21b70d25016731768db1f"
28
+ MIN_SCORE = 0.30 # Classroom heuristic, not a confidence threshold.
29
+ NO_ANSWER = "I cannot answer this from the supplied passages."
30
 
31
+ corpus = []
32
+ passage_embeddings = None
33
+ embedder = None
34
+ tokenizer = None
35
+ generator = None
36
 
 
 
 
 
 
37
 
38
+ # -----------------------------------------------------------
39
+ # Manual RAG: passage loading, embedding, retrieval, generation
40
+ # -----------------------------------------------------------
41
 
42
+ def load_retriever():
43
+ """Stream 30 unique SQuAD passages and embed them using CPU."""
44
+ global corpus, passage_embeddings, embedder
45
+ if embedder is not None and passage_embeddings is not None:
46
+ return passage_embeddings.shape
47
 
48
+ model = SentenceTransformer(EMBEDDING_MODEL, device="cpu")
49
+ rows = load_dataset(
50
+ DATASET_ID,
51
+ split="train",
52
+ revision=DATASET_REVISION,
53
+ streaming=True,
54
+ )
55
+ selected = []
56
+ seen = set()
57
+ title_counts = {}
58
 
59
+ for row in rows.take(6000):
60
+ title = row["title"].replace("_", " ")
61
+ context = row["context"].strip()
62
+ if (
63
+ context in seen
64
+ or title_counts.get(title, 0) >= 3
65
+ or len(title) > 35
66
+ or title == "Genocide"
67
+ ):
68
+ continue
69
+ token_count = len(
70
+ model.tokenizer(
71
+ title + ". " + context,
72
+ truncation=False,
73
+ verbose=False,
74
+ )["input_ids"]
75
+ )
76
+ if token_count > 200:
77
+ continue
78
+ selected.append({
79
+ "id": f"P{len(selected) + 1:02d}",
80
+ "title": title,
81
+ "text": context,
82
+ "source": "SQuAD train / Wikipedia: " + title,
83
+ })
84
+ seen.add(context)
85
+ title_counts[title] = title_counts.get(title, 0) + 1
86
+ if len(selected) == 30:
87
+ break
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
+ if len(selected) != 30:
90
+ raise RuntimeError("Could not retrieve 30 passages from SQuAD.")
91
 
92
+ embeddings = model.encode(
93
+ [p["title"] + ". " + p["text"] for p in selected],
94
+ normalize_embeddings=True,
95
+ convert_to_numpy=True,
96
+ show_progress_bar=False,