Haider67 commited on
Commit
b5cb44c
·
verified ·
1 Parent(s): 5369864

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -34
app.py CHANGED
@@ -15,14 +15,14 @@ from ddgs import DDGS
15
  DEFAULT_API_URL = "https://hf.space"
16
  MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"
17
 
18
- # Load models at startup so GPU time is used only for inference
19
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
20
  model = AutoModelForCausalLM.from_pretrained(
21
  MODEL_ID,
22
  torch_dtype=torch.bfloat16,
23
  device_map="auto",
24
  )
25
- asr_pipe = pipeline("automatic-speech-recognition", model="openai/whisper-small")
 
26
 
27
  def download_file(task_id: str, file_name: str) -> str | None:
28
  if not file_name:
@@ -39,7 +39,7 @@ def download_file(task_id: str, file_name: str) -> str | None:
39
  pass
40
  return None
41
 
42
- def read_non_audio_file(file_path: str) -> str:
43
  if not file_path or not os.path.exists(file_path):
44
  return ""
45
  ext = os.path.splitext(file_path)[1].lower()
@@ -52,6 +52,9 @@ def read_non_audio_file(file_path: str) -> str:
52
  elif ext in [".xlsx", ".xls"]:
53
  df = pd.read_excel(file_path)
54
  return f"Excel Table Contents:\n{df.to_string(index=False)}"
 
 
 
55
  elif ext in [".txt", ".csv", ".json"]:
56
  with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
57
  return f.read()[:6000]
@@ -60,7 +63,6 @@ def read_non_audio_file(file_path: str) -> str:
60
  return f"[Attached file: {os.path.basename(file_path)}]"
61
 
62
  def build_clean_query(question: str) -> str:
63
- # Strip conversational filler so DuckDuckGo & Wikipedia return exact hits
64
  q = re.sub(r"https?://\S+", "", question)
65
  words = [w for w in re.findall(r"[A-Za-z0-9'-]+", q) if len(w) > 2]
66
  return " ".join(words[:10])
@@ -102,23 +104,11 @@ def extract_final_answer(raw_text: str) -> str:
102
  lines = [line.strip() for line in raw_text.strip().splitlines() if line.strip()]
103
  return lines[-1] if lines else raw_text.strip()
104
 
105
- @spaces.GPU(duration=180)
106
- def process_all_on_gpu(items_with_files: list[dict]) -> list[str]:
107
- asr_pipe.model.to("cuda")
108
  answers = []
109
- for entry in items_with_files:
110
- fp = entry.get("file_path")
111
- if fp and fp.lower().endswith(".mp3"):
112
- try:
113
- transcript = asr_pipe(fp)["text"]
114
- entry["context"] += f"\n\nAudio Transcript ({os.path.basename(fp)}):\n{transcript}"
115
- except Exception as e:
116
- entry["context"] += f"\n\nAudio error: {e}"
117
-
118
- user_prompt = entry["question"]
119
- if entry["context"]:
120
- user_prompt += f"\n\n--- Supporting Context ---\n{entry['context']}"
121
-
122
  messages = [
123
  {"role": "system", "content": SYSTEM_PROMPT},
124
  {"role": "user", "content": user_prompt},
@@ -127,7 +117,7 @@ def process_all_on_gpu(items_with_files: list[dict]) -> list[str]:
127
  inputs = tokenizer([text], return_tensors="pt").to("cuda")
128
 
129
  with torch.no_grad():
130
- outputs = model.generate(**inputs, max_new_tokens=200, do_sample=False)
131
 
132
  generated_tokens = outputs[0][inputs.input_ids.shape[1]:]
133
  raw_response = tokenizer.decode(generated_tokens, skip_special_tokens=True)
@@ -160,8 +150,9 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
160
  if not questions_data:
161
  return "Error: Could not load questions.", None
162
 
163
- # Download files & gather web/wiki search context on CPU first
164
- prepared_items = []
 
165
  for item in questions_data:
166
  task_id = item.get("task_id")
167
  question_text = item.get("question")
@@ -169,24 +160,21 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
169
  if not task_id or question_text is None:
170
  continue
171
  fp = download_file(task_id, file_name)
172
- ctx = read_non_audio_file(fp) if fp else search_web_and_wiki(question_text)
173
- prepared_items.append({
174
- "task_id": task_id,
175
- "question": question_text,
176
- "file_path": fp,
177
- "context": ctx,
178
- })
179
 
180
  try:
181
- final_answers = process_all_on_gpu(prepared_items)
182
  except Exception as e:
183
  return f"ZeroGPU execution failed: {e}", None
184
 
185
  results_log = []
186
  answers_payload = []
187
- for entry, ans in zip(prepared_items, final_answers):
188
- answers_payload.append({"task_id": entry["task_id"], "submitted_answer": ans})
189
- results_log.append({"Task ID": entry["task_id"], "Question": entry["question"], "Submitted Answer": ans})
190
 
191
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
192
  try:
 
15
  DEFAULT_API_URL = "https://hf.space"
16
  MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"
17
 
 
18
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
19
  model = AutoModelForCausalLM.from_pretrained(
20
  MODEL_ID,
21
  torch_dtype=torch.bfloat16,
22
  device_map="auto",
23
  )
24
+ # Keep Whisper on CPU so it consumes 0 seconds of ZeroGPU quota
25
+ asr_pipe = pipeline("automatic-speech-recognition", model="openai/whisper-small", device="cpu")
26
 
27
  def download_file(task_id: str, file_name: str) -> str | None:
28
  if not file_name:
 
39
  pass
40
  return None
41
 
42
+ def read_attached_file(file_path: str) -> str:
43
  if not file_path or not os.path.exists(file_path):
44
  return ""
45
  ext = os.path.splitext(file_path)[1].lower()
 
52
  elif ext in [".xlsx", ".xls"]:
53
  df = pd.read_excel(file_path)
54
  return f"Excel Table Contents:\n{df.to_string(index=False)}"
55
+ elif ext == ".mp3":
56
+ transcript = asr_pipe(file_path)["text"]
57
+ return f"Audio Transcript ({os.path.basename(file_path)}):\n{transcript}"
58
  elif ext in [".txt", ".csv", ".json"]:
59
  with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
60
  return f.read()[:6000]
 
63
  return f"[Attached file: {os.path.basename(file_path)}]"
64
 
65
  def build_clean_query(question: str) -> str:
 
66
  q = re.sub(r"https?://\S+", "", question)
67
  words = [w for w in re.findall(r"[A-Za-z0-9'-]+", q) if len(w) > 2]
68
  return " ".join(words[:10])
 
104
  lines = [line.strip() for line in raw_text.strip().splitlines() if line.strip()]
105
  return lines[-1] if lines else raw_text.strip()
106
 
107
+ # Requests only 90s so it fits inside your remaining 190s free quota!
108
+ @spaces.GPU(duration=90)
109
+ def process_all_on_gpu(prompts: list[str]) -> list[str]:
110
  answers = []
111
+ for user_prompt in prompts:
 
 
 
 
 
 
 
 
 
 
 
 
112
  messages = [
113
  {"role": "system", "content": SYSTEM_PROMPT},
114
  {"role": "user", "content": user_prompt},
 
117
  inputs = tokenizer([text], return_tensors="pt").to("cuda")
118
 
119
  with torch.no_grad():
120
+ outputs = model.generate(**inputs, max_new_tokens=160, do_sample=False)
121
 
122
  generated_tokens = outputs[0][inputs.input_ids.shape[1]:]
123
  raw_response = tokenizer.decode(generated_tokens, skip_special_tokens=True)
 
150
  if not questions_data:
151
  return "Error: Could not load questions.", None
152
 
153
+ # All file reading, Whisper transcription, and web/Wiki search run on CPU first
154
+ valid_items = []
155
+ prompts = []
156
  for item in questions_data:
157
  task_id = item.get("task_id")
158
  question_text = item.get("question")
 
160
  if not task_id or question_text is None:
161
  continue
162
  fp = download_file(task_id, file_name)
163
+ ctx = read_attached_file(fp) if fp else search_web_and_wiki(question_text)
164
+ user_prompt = question_text + (f"\n\n--- Supporting Context ---\n{ctx}" if ctx else "")
165
+ valid_items.append(item)
166
+ prompts.append(user_prompt)
 
 
 
167
 
168
  try:
169
+ final_answers = process_all_on_gpu(prompts)
170
  except Exception as e:
171
  return f"ZeroGPU execution failed: {e}", None
172
 
173
  results_log = []
174
  answers_payload = []
175
+ for item, ans in zip(valid_items, final_answers):
176
+ answers_payload.append({"task_id": item["task_id"], "submitted_answer": ans})
177
+ results_log.append({"Task ID": item["task_id"], "Question": item["question"], "Submitted Answer": ans})
178
 
179
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
180
  try: