knt21 commited on
Commit
abcb1a8
·
verified ·
1 Parent(s): af22204

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +128 -0
app.py ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import gradio as gr
3
+ import pandas as pd
4
+ import json
5
+ import inspect
6
+
7
+ # --- Basic Agent Definition ---
8
+ class BasicAgent:
9
+ def __init__(self):
10
+ print("BasicAgent initialized.")
11
+
12
+ def __call__(self, question: str) -> str:
13
+ print(f"Agent received question (first 50 chars): {question[:50]}...")
14
+ fixed_answer = "This is a default answer."
15
+ print(f"Agent returning fixed answer: {fixed_answer}")
16
+ return fixed_answer
17
+
18
+
19
+ # --- Main Function: run_and_save ---
20
+ def run_and_save(profile: gr.OAuthProfile | None, task_id: int):
21
+ """
22
+ Loads questions.json, finds the question by task_id,
23
+ runs the agent, and appends the answer to result_log.json.
24
+ """
25
+ # --- Authentication Check ---
26
+ if not profile:
27
+ print("User not logged in.")
28
+ return "Please Login to Hugging Face with the button.", None
29
+
30
+ username = profile.username
31
+ print(f"✅ User logged in: {username}")
32
+
33
+ # --- Instantiate Agent ---
34
+ try:
35
+ agent = BasicAgent()
36
+ except Exception as e:
37
+ return f"Error initializing agent: {e}", None
38
+
39
+ # --- Load Questions ---
40
+ questions_path = "questions.json"
41
+ if not os.path.exists(questions_path):
42
+ return f"❌ {questions_path} not found.", None
43
+
44
+ try:
45
+ with open(questions_path, "r", encoding="utf-8") as f:
46
+ questions_data = json.load(f)
47
+ except json.JSONDecodeError as e:
48
+ return f"Error decoding {questions_path}: {e}", None
49
+
50
+ if not isinstance(questions_data, list):
51
+ return "Invalid format: questions.json must contain a list.", None
52
+
53
+ # --- Find Question by Task ID ---
54
+ question_item = next((q for q in questions_data if q.get("task_id") == task_id), None)
55
+ if not question_item:
56
+ return f"No question found for task_id {task_id}.", None
57
+
58
+ question_text = question_item.get("question", "")
59
+ print(f"🟦 Running agent for task_id {task_id}...")
60
+
61
+ # --- Run Agent ---
62
+ try:
63
+ submitted_answer = agent(question_text)
64
+ result = {
65
+ "Task ID": task_id,
66
+ "Question": question_text,
67
+ "Submitted Answer": submitted_answer
68
+ }
69
+ except Exception as e:
70
+ result = {
71
+ "Task ID": task_id,
72
+ "Question": question_text,
73
+ "Submitted Answer": f"AGENT ERROR: {e}"
74
+ }
75
+
76
+ # --- Save to result_log.json ---
77
+ result_log_path = "result_log.json"
78
+ if os.path.exists(result_log_path):
79
+ try:
80
+ with open(result_log_path, "r", encoding="utf-8") as f:
81
+ result_log = json.load(f)
82
+ if not isinstance(result_log, list):
83
+ result_log = []
84
+ except Exception:
85
+ result_log = []
86
+ else:
87
+ result_log = []
88
+
89
+ result_log.append(result)
90
+
91
+ with open(result_log_path, "w", encoding="utf-8") as f:
92
+ json.dump(result_log, f, indent=4, ensure_ascii=False)
93
+
94
+ print(f"✅ Result saved to {result_log_path}")
95
+
96
+ results_df = pd.DataFrame([result])
97
+ return f"✅ Answer saved locally for task_id {task_id}", results_df
98
+
99
+
100
+ # --- Gradio Interface ---
101
+ with gr.Blocks() as demo:
102
+ gr.Markdown("# Local Agent Runner & Saver")
103
+ gr.Markdown(
104
+ """
105
+ **Instructions:**
106
+ 1. Login to Hugging Face using the button below.
107
+ 2. Enter the Task ID from your `questions.json`.
108
+ 3. Click **Run Agent & Save Answer**.
109
+ 4. The result will be appended to `result_log.json` for manual upload.
110
+ """
111
+ )
112
+
113
+ profile = gr.LoginButton()
114
+ task_id_input = gr.Number(label="Enter Task ID", precision=0)
115
+ run_button = gr.Button("Run Agent & Save Answer")
116
+
117
+ status_output = gr.Textbox(label="Status", lines=3, interactive=False)
118
+ results_table = gr.DataFrame(label="Result Log (Latest Entry)")
119
+
120
+ run_button.click(
121
+ fn=run_and_save,
122
+ inputs=[profile, task_id_input],
123
+ outputs=[status_output, results_table]
124
+ )
125
+
126
+ if __name__ == "__main__":
127
+ print("Launching Gradio interface...")
128
+ demo.launch(debug=True, share=False)