Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -16,7 +16,6 @@ from ddgs import DDGS
|
|
| 16 |
DEFAULT_API_URL = "https://hf.space"
|
| 17 |
MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"
|
| 18 |
|
| 19 |
-
# Load on plain CPU at startup (NO device_map="auto" so ZeroGPU forks cleanly)
|
| 20 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 21 |
model = AutoModelForCausalLM.from_pretrained(
|
| 22 |
MODEL_ID,
|
|
@@ -42,7 +41,7 @@ def download_file(task_id: str, file_name: str) -> str | None:
|
|
| 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).lower()
|
| 46 |
try:
|
| 47 |
if ext == ".py":
|
| 48 |
res = subprocess.run(["python3", file_path], capture_output=True, text=True, timeout=15)
|
|
@@ -59,7 +58,7 @@ def read_attached_file(file_path: str) -> str:
|
|
| 59 |
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
| 60 |
return f.read()[:6000]
|
| 61 |
except Exception as e:
|
| 62 |
-
return f"File read error: {e}"
|
| 63 |
return f"[Attached file: {os.path.basename(file_path)}]"
|
| 64 |
|
| 65 |
def build_clean_query(question: str) -> str:
|
|
@@ -112,64 +111,61 @@ def process_all_on_gpu(prompts: list[str]) -> list[str]:
|
|
| 112 |
with torch.no_grad():
|
| 113 |
outputs = model.generate(**inputs, max_new_tokens=64, do_sample=False)
|
| 114 |
|
| 115 |
-
generated_tokens = outputs[inputs.input_ids.shape:]
|
| 116 |
ans = tokenizer.decode(generated_tokens, skip_special_tokens=True).strip().strip('"').strip("'")
|
| 117 |
answers.append(ans)
|
| 118 |
|
| 119 |
return answers
|
| 120 |
|
| 121 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
| 122 |
-
space_id = os.getenv("SPACE_ID")
|
| 123 |
-
if not profile:
|
| 124 |
-
return "Please Login to Hugging Face with the button.", None
|
| 125 |
-
|
| 126 |
-
username = f"{profile.username}"
|
| 127 |
-
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 128 |
-
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 129 |
-
agent_code = f"https://huggingface.co{space_id}/tree/main"
|
| 130 |
-
|
| 131 |
-
questions_data = None
|
| 132 |
try:
|
| 133 |
-
|
| 134 |
-
if
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
| 139 |
-
|
| 140 |
-
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
|
| 144 |
-
|
| 145 |
-
|
| 146 |
-
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
|
| 151 |
-
|
| 152 |
-
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
| 156 |
-
|
| 157 |
-
valid_items
|
| 158 |
-
prompts
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
-
try:
|
| 161 |
final_answers = process_all_on_gpu(prompts)
|
| 162 |
-
except Exception:
|
| 163 |
-
return f"ZeroGPU execution failed:\n{traceback.format_exc()}", None
|
| 164 |
|
| 165 |
-
|
| 166 |
-
|
| 167 |
-
|
| 168 |
-
|
| 169 |
-
|
| 170 |
|
| 171 |
-
|
| 172 |
-
try:
|
| 173 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 174 |
response.raise_for_status()
|
| 175 |
result_data = response.json()
|
|
@@ -181,16 +177,15 @@ def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
| 181 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 182 |
)
|
| 183 |
return final_status, pd.DataFrame(results_log)
|
| 184 |
-
|
| 185 |
-
|
| 186 |
-
|
| 187 |
-
return f"Submission Failed: {e}", pd.DataFrame(results_log)
|
| 188 |
|
| 189 |
with gr.Blocks() as demo:
|
| 190 |
gr.Markdown("# Multi-Modal ZeroGPU Agent Evaluation Runner")
|
| 191 |
gr.LoginButton()
|
| 192 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 193 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=
|
| 194 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 195 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 196 |
|
|
|
|
| 16 |
DEFAULT_API_URL = "https://hf.space"
|
| 17 |
MODEL_ID = "Qwen/Qwen2.5-7B-Instruct"
|
| 18 |
|
|
|
|
| 19 |
tokenizer = AutoTokenizer.from_pretrained(MODEL_ID)
|
| 20 |
model = AutoModelForCausalLM.from_pretrained(
|
| 21 |
MODEL_ID,
|
|
|
|
| 41 |
def read_attached_file(file_path: str) -> str:
|
| 42 |
if not file_path or not os.path.exists(file_path):
|
| 43 |
return ""
|
| 44 |
+
ext = os.path.splitext(file_path)[1].lower()
|
| 45 |
try:
|
| 46 |
if ext == ".py":
|
| 47 |
res = subprocess.run(["python3", file_path], capture_output=True, text=True, timeout=15)
|
|
|
|
| 58 |
with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
|
| 59 |
return f.read()[:6000]
|
| 60 |
except Exception as e:
|
| 61 |
+
return f"File read error ({os.path.basename(file_path)}): {e}"
|
| 62 |
return f"[Attached file: {os.path.basename(file_path)}]"
|
| 63 |
|
| 64 |
def build_clean_query(question: str) -> str:
|
|
|
|
| 111 |
with torch.no_grad():
|
| 112 |
outputs = model.generate(**inputs, max_new_tokens=64, do_sample=False)
|
| 113 |
|
| 114 |
+
generated_tokens = outputs[0][inputs.input_ids.shape[1]:]
|
| 115 |
ans = tokenizer.decode(generated_tokens, skip_special_tokens=True).strip().strip('"').strip("'")
|
| 116 |
answers.append(ans)
|
| 117 |
|
| 118 |
return answers
|
| 119 |
|
| 120 |
def run_and_submit_all(profile: gr.OAuthProfile | None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 121 |
try:
|
| 122 |
+
space_id = os.getenv("SPACE_ID")
|
| 123 |
+
if not profile:
|
| 124 |
+
return "Please Login to Hugging Face with the button.", None
|
| 125 |
+
|
| 126 |
+
username = f"{profile.username}"
|
| 127 |
+
questions_url = f"{DEFAULT_API_URL}/questions"
|
| 128 |
+
submit_url = f"{DEFAULT_API_URL}/submit"
|
| 129 |
+
agent_code = f"https://huggingface.co{space_id}/tree/main"
|
| 130 |
+
|
| 131 |
+
questions_data = None
|
| 132 |
+
try:
|
| 133 |
+
response = requests.get(questions_url, timeout=15)
|
| 134 |
+
if response.status_code == 200 and response.text.strip():
|
| 135 |
+
questions_data = response.json()
|
| 136 |
+
except Exception:
|
| 137 |
+
pass
|
| 138 |
+
|
| 139 |
+
if not questions_data and os.path.exists("questions.json"):
|
| 140 |
+
with open("questions.json", "r", encoding="utf-8") as f:
|
| 141 |
+
questions_data = json.load(f)
|
| 142 |
+
|
| 143 |
+
if not questions_data:
|
| 144 |
+
return "Error: Could not load questions.", None
|
| 145 |
+
|
| 146 |
+
valid_items = []
|
| 147 |
+
prompts = []
|
| 148 |
+
for item in questions_data:
|
| 149 |
+
task_id = item.get("task_id")
|
| 150 |
+
question_text = item.get("question")
|
| 151 |
+
file_name = item.get("file_name", "")
|
| 152 |
+
if not task_id or question_text is None:
|
| 153 |
+
continue
|
| 154 |
+
fp = download_file(task_id, file_name)
|
| 155 |
+
ctx = read_attached_file(fp) if fp else search_web_and_wiki(question_text)
|
| 156 |
+
user_prompt = question_text + (f"\n\n--- Supporting Context ---\n{ctx}" if ctx else "")
|
| 157 |
+
valid_items.append(item)
|
| 158 |
+
prompts.append(user_prompt)
|
| 159 |
|
|
|
|
| 160 |
final_answers = process_all_on_gpu(prompts)
|
|
|
|
|
|
|
| 161 |
|
| 162 |
+
results_log = []
|
| 163 |
+
answers_payload = []
|
| 164 |
+
for item, ans in zip(valid_items, final_answers):
|
| 165 |
+
answers_payload.append({"task_id": item["task_id"], "submitted_answer": ans})
|
| 166 |
+
results_log.append({"Task ID": item["task_id"], "Question": item["question"], "Submitted Answer": ans})
|
| 167 |
|
| 168 |
+
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
|
|
|
| 169 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
| 170 |
response.raise_for_status()
|
| 171 |
result_data = response.json()
|
|
|
|
| 177 |
f"Message: {result_data.get('message', 'No message received.')}"
|
| 178 |
)
|
| 179 |
return final_status, pd.DataFrame(results_log)
|
| 180 |
+
|
| 181 |
+
except Exception:
|
| 182 |
+
return f"Detailed Error:\n{traceback.format_exc()}", None
|
|
|
|
| 183 |
|
| 184 |
with gr.Blocks() as demo:
|
| 185 |
gr.Markdown("# Multi-Modal ZeroGPU Agent Evaluation Runner")
|
| 186 |
gr.LoginButton()
|
| 187 |
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 188 |
+
status_output = gr.Textbox(label="Run Status / Submission Result", lines=8, interactive=False)
|
| 189 |
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 190 |
run_button.click(fn=run_and_submit_all, outputs=[status_output, results_table])
|
| 191 |
|