bash98 commited on
Commit
0f26896
·
verified ·
1 Parent(s): 5d4f5f3

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +28 -97
app.py CHANGED
@@ -1,162 +1,93 @@
1
-
2
- """
3
- Document Q&A with Manual RAG
4
- Hugging Face Spaces - CPU Compatible Version
5
- """
6
 
7
  import os
8
  import traceback
9
 
10
- # Force CPU execution before loading ML libraries
11
  os.environ["CUDA_VISIBLE_DEVICES"] = ""
12
- os.environ["TOKENIZERS_PARALLELISM"] = "false"
13
 
14
  import gradio as gr
15
 
16
- from rag_core import (
17
- load_retriever,
18
- answer_question,
19
- display_evidence,
20
- )
21
 
22
 
23
  def respond(question, retrieval_only):
24
- """Retrieve evidence and optionally generate an answer."""
25
-
26
- if not question or not question.strip():
27
- return (
28
- "Please enter a question.",
29
- "",
30
- "Input error"
31
- )
32
 
33
  try:
34
  result = answer_question(
35
- question.strip(),
36
- retrieval_only=bool(retrieval_only)
37
- )
38
-
39
- return (
40
- result.get("answer", "No answer generated."),
41
- display_evidence(result),
42
- result.get("status", "Completed")
43
  )
 
44
 
45
  except (ValueError, RuntimeError) as error:
46
  traceback.print_exc()
 
47
 
48
- return (
49
- f"Error: {str(error)}",
50
- "",
51
- "Input or setup error"
52
- )
53
-
54
- except Exception as error:
55
  traceback.print_exc()
56
-
57
  return (
58
- "Dataset/model access or generation failed. "
59
- f"Details: {str(error)}",
60
  "",
61
- "Model error"
62
  )
63
 
64
 
65
  def make_demo():
66
- """Create the Gradio interface."""
67
-
68
  return gr.Interface(
69
  fn=respond,
70
-
71
  inputs=[
72
  gr.Textbox(
73
  label="Question",
74
  placeholder="Which company produces the iPod?",
75
- lines=2
76
  ),
77
-
78
  gr.Checkbox(
79
  label="Retrieval only (skip answer generation)",
80
- value=False
81
- )
82
  ],
83
-
84
  outputs=[
85
- gr.Textbox(
86
- label="Answer - verify against evidence",
87
- lines=5
88
- ),
89
-
90
- gr.Textbox(
91
- label="Source passages and similarity scores",
92
- lines=15
93
- ),
94
-
95
- gr.Textbox(
96
- label="Run status",
97
- lines=2
98
- )
99
  ],
100
-
101
  title="Document Q&A with Manual RAG",
102
-
103
  description=(
104
- "Ask questions about 30 SQuAD/Wikipedia passages "
105
- "loaded from Hugging Face. "
106
- "The application retrieves relevant evidence "
107
- "and optionally generates an answer. "
108
- "Always verify answers against the sources."
109
  ),
110
-
111
  examples=[
112
  ["Which company produces the iPod?", False],
113
  ["At what age did Frédéric move to Paris?", False],
114
- ["What is Beyoncé's private mobile phone number?", False]
115
  ],
116
-
117
  cache_examples=False,
118
-
119
- flagging_mode="never"
120
  )
121
 
122
 
123
  def main():
124
- """Initialize retrieval system and launch the application."""
125
-
126
- print("=" * 50)
127
- print("Initializing Document Q&A with Manual RAG")
128
- print("Execution mode: CPU")
129
- print("=" * 50)
130
-
131
  try:
132
- print("Loading retriever...")
133
-
134
- info = load_retriever()
135
-
136
- print(f"Retriever initialized successfully: {info}")
137
-
138
  except Exception:
139
  print("Failed to initialize retriever.")
140
  traceback.print_exc()
141
  raise
142
 
143
- print("Creating Gradio interface...")
144
-
145
  demo = make_demo()
146
-
147
- demo.queue(
148
- default_concurrency_limit=1,
149
- max_size=20
150
- )
151
-
152
- print("Starting Gradio application...")
153
-
154
  demo.launch(
155
  server_name="0.0.0.0",
156
  server_port=int(os.environ.get("PORT", "7860")),
157
  share=False,
158
  show_error=True,
159
- ssr_mode=False
160
  )
161
 
162
 
 
1
+ """Document Q&A with Manual RAG - Hugging Face CPU Basic."""
 
 
 
 
2
 
3
  import os
4
  import traceback
5
 
6
+ # Set this before importing the ML libraries used by rag_core.
7
  os.environ["CUDA_VISIBLE_DEVICES"] = ""
8
+ os.environ.setdefault("TOKENIZERS_PARALLELISM", "false")
9
 
10
  import gradio as gr
11
 
12
+ from rag_core import load_retriever, answer_question, display_evidence
 
 
 
 
13
 
14
 
15
  def respond(question, retrieval_only):
16
+ """Retrieve evidence and optionally generate a grounded answer."""
17
+ if not isinstance(question, str) or not question.strip():
18
+ return "Please enter a question.", "", "Input error"
 
 
 
 
 
19
 
20
  try:
21
  result = answer_question(
22
+ question.strip(), retrieval_only=bool(retrieval_only)
 
 
 
 
 
 
 
23
  )
24
+ return result["answer"], display_evidence(result), result["status"]
25
 
26
  except (ValueError, RuntimeError) as error:
27
  traceback.print_exc()
28
+ return str(error), "", "Input or setup error"
29
 
30
+ except Exception:
 
 
 
 
 
 
31
  traceback.print_exc()
 
32
  return (
33
+ "Dataset/model access or generation failed. Check the Space logs.",
 
34
  "",
35
+ "Model error",
36
  )
37
 
38
 
39
  def make_demo():
 
 
40
  return gr.Interface(
41
  fn=respond,
 
42
  inputs=[
43
  gr.Textbox(
44
  label="Question",
45
  placeholder="Which company produces the iPod?",
46
+ lines=2,
47
  ),
 
48
  gr.Checkbox(
49
  label="Retrieval only (skip answer generation)",
50
+ value=False,
51
+ ),
52
  ],
 
53
  outputs=[
54
+ gr.Textbox(label="Answer - verify against the evidence", lines=5),
55
+ gr.Textbox(label="Source passages and similarity scores", lines=15),
56
+ gr.Textbox(label="Run status"),
 
 
 
 
 
 
 
 
 
 
 
57
  ],
 
58
  title="Document Q&A with Manual RAG",
 
59
  description=(
60
+ "Ask questions about 30 SQuAD/Wikipedia passages loaded from "
61
+ "Hugging Face. The app retrieves evidence and optionally generates "
62
+ "an answer. Always verify answers against the sources."
 
 
63
  ),
 
64
  examples=[
65
  ["Which company produces the iPod?", False],
66
  ["At what age did Frédéric move to Paris?", False],
67
+ ["What is Beyoncé's private mobile phone number?", False],
68
  ],
 
69
  cache_examples=False,
 
 
70
  )
71
 
72
 
73
  def main():
74
+ print("Initializing Document Q&A with Manual RAG (CPU mode)...")
 
 
 
 
 
 
75
  try:
76
+ shape = load_retriever()
77
+ print("Retriever initialized:", shape)
 
 
 
 
78
  except Exception:
79
  print("Failed to initialize retriever.")
80
  traceback.print_exc()
81
  raise
82
 
 
 
83
  demo = make_demo()
84
+ demo.queue(default_concurrency_limit=1, max_size=20)
 
 
 
 
 
 
 
85
  demo.launch(
86
  server_name="0.0.0.0",
87
  server_port=int(os.environ.get("PORT", "7860")),
88
  share=False,
89
  show_error=True,
90
+ ssr_mode=False,
91
  )
92
 
93