feat: replaced print with logger in app module.
Browse files
app.py
CHANGED
@@ -3,6 +3,11 @@ import gradio as gr
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
|
|
|
|
|
|
|
|
|
|
6 |
|
7 |
# (Keep Constants as is)
|
8 |
# --- Constants ---
|
@@ -12,11 +17,11 @@ DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
|
|
12 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
13 |
class BasicAgent:
|
14 |
def __init__(self):
|
15 |
-
|
16 |
def __call__(self, question: str) -> str:
|
17 |
-
|
18 |
fixed_answer = "This is a default answer."
|
19 |
-
|
20 |
return fixed_answer
|
21 |
|
22 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
@@ -29,9 +34,9 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
29 |
|
30 |
if profile:
|
31 |
username= f"{profile.username}"
|
32 |
-
|
33 |
else:
|
34 |
-
|
35 |
return "Please Login to Hugging Face with the button.", None
|
36 |
|
37 |
api_url = DEFAULT_API_URL
|
@@ -42,62 +47,62 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
42 |
try:
|
43 |
agent = BasicAgent()
|
44 |
except Exception as e:
|
45 |
-
|
46 |
return f"Error initializing agent: {e}", None
|
47 |
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
48 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
49 |
-
|
50 |
|
51 |
# 2. Fetch Questions
|
52 |
-
|
53 |
try:
|
54 |
response = requests.get(questions_url, timeout=15)
|
55 |
response.raise_for_status()
|
56 |
questions_data = response.json()
|
57 |
if not questions_data:
|
58 |
-
|
59 |
return "Fetched questions list is empty or invalid format.", None
|
60 |
-
|
61 |
except requests.exceptions.RequestException as e:
|
62 |
-
|
63 |
return f"Error fetching questions: {e}", None
|
64 |
except requests.exceptions.JSONDecodeError as e:
|
65 |
-
|
66 |
-
|
67 |
return f"Error decoding server response for questions: {e}", None
|
68 |
except Exception as e:
|
69 |
-
|
70 |
return f"An unexpected error occurred fetching questions: {e}", None
|
71 |
|
72 |
# 3. Run your Agent
|
73 |
results_log = []
|
74 |
answers_payload = []
|
75 |
-
|
76 |
for item in questions_data:
|
77 |
task_id = item.get("task_id")
|
78 |
question_text = item.get("question")
|
79 |
if not task_id or question_text is None:
|
80 |
-
|
81 |
continue
|
82 |
try:
|
83 |
submitted_answer = agent(question_text)
|
84 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
85 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
86 |
except Exception as e:
|
87 |
-
|
88 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
89 |
|
90 |
if not answers_payload:
|
91 |
-
|
92 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
93 |
|
94 |
# 4. Prepare Submission
|
95 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
96 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
97 |
-
|
98 |
|
99 |
# 5. Submit
|
100 |
-
|
101 |
try:
|
102 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
103 |
response.raise_for_status()
|
@@ -109,7 +114,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
109 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
110 |
f"Message: {result_data.get('message', 'No message received.')}"
|
111 |
)
|
112 |
-
|
113 |
results_df = pd.DataFrame(results_log)
|
114 |
return final_status, results_df
|
115 |
except requests.exceptions.HTTPError as e:
|
@@ -120,22 +125,22 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
120 |
except requests.exceptions.JSONDecodeError:
|
121 |
error_detail += f" Response: {e.response.text[:500]}"
|
122 |
status_message = f"Submission Failed: {error_detail}"
|
123 |
-
|
124 |
results_df = pd.DataFrame(results_log)
|
125 |
return status_message, results_df
|
126 |
except requests.exceptions.Timeout:
|
127 |
status_message = "Submission Failed: The request timed out."
|
128 |
-
|
129 |
results_df = pd.DataFrame(results_log)
|
130 |
return status_message, results_df
|
131 |
except requests.exceptions.RequestException as e:
|
132 |
status_message = f"Submission Failed: Network error - {e}"
|
133 |
-
|
134 |
results_df = pd.DataFrame(results_log)
|
135 |
return status_message, results_df
|
136 |
except Exception as e:
|
137 |
status_message = f"An unexpected error occurred during submission: {e}"
|
138 |
-
|
139 |
results_df = pd.DataFrame(results_log)
|
140 |
return status_message, results_df
|
141 |
|
@@ -172,25 +177,25 @@ with gr.Blocks() as demo:
|
|
172 |
)
|
173 |
|
174 |
if __name__ == "__main__":
|
175 |
-
|
176 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
177 |
space_host_startup = os.getenv("SPACE_HOST")
|
178 |
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
179 |
|
180 |
if space_host_startup:
|
181 |
-
|
182 |
-
|
183 |
else:
|
184 |
-
|
185 |
|
186 |
-
if space_id_startup: #
|
187 |
-
|
188 |
-
|
189 |
-
|
190 |
else:
|
191 |
-
|
192 |
|
193 |
-
|
194 |
|
195 |
-
|
196 |
demo.launch(debug=True, share=False)
|
|
|
3 |
import requests
|
4 |
import inspect
|
5 |
import pandas as pd
|
6 |
+
import logging
|
7 |
+
|
8 |
+
# Setup logger
|
9 |
+
logging.basicConfig(level=logging.INFO)
|
10 |
+
logger = logging.getLogger(__name__)
|
11 |
|
12 |
# (Keep Constants as is)
|
13 |
# --- Constants ---
|
|
|
17 |
# ----- THIS IS WERE YOU CAN BUILD WHAT YOU WANT ------
|
18 |
class BasicAgent:
|
19 |
def __init__(self):
|
20 |
+
logger.info("BasicAgent initialized.")
|
21 |
def __call__(self, question: str) -> str:
|
22 |
+
logger.info(f"Agent received question (first 50 chars): {question[:50]}...")
|
23 |
fixed_answer = "This is a default answer."
|
24 |
+
logger.info(f"Agent returning fixed answer: {fixed_answer}")
|
25 |
return fixed_answer
|
26 |
|
27 |
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
|
|
34 |
|
35 |
if profile:
|
36 |
username= f"{profile.username}"
|
37 |
+
logger.info(f"User logged in: {username}")
|
38 |
else:
|
39 |
+
logger.info("User not logged in.")
|
40 |
return "Please Login to Hugging Face with the button.", None
|
41 |
|
42 |
api_url = DEFAULT_API_URL
|
|
|
47 |
try:
|
48 |
agent = BasicAgent()
|
49 |
except Exception as e:
|
50 |
+
logger.info(f"Error instantiating agent: {e}")
|
51 |
return f"Error initializing agent: {e}", None
|
52 |
# In the case of an app running as a hugging Face space, this link points toward your codebase ( usefull for others so please keep it public)
|
53 |
agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
|
54 |
+
logger.info(agent_code)
|
55 |
|
56 |
# 2. Fetch Questions
|
57 |
+
logger.info(f"Fetching questions from: {questions_url}")
|
58 |
try:
|
59 |
response = requests.get(questions_url, timeout=15)
|
60 |
response.raise_for_status()
|
61 |
questions_data = response.json()
|
62 |
if not questions_data:
|
63 |
+
logger.info("Fetched questions list is empty.")
|
64 |
return "Fetched questions list is empty or invalid format.", None
|
65 |
+
logger.info(f"Fetched {len(questions_data)} questions.")
|
66 |
except requests.exceptions.RequestException as e:
|
67 |
+
logger.info(f"Error fetching questions: {e}")
|
68 |
return f"Error fetching questions: {e}", None
|
69 |
except requests.exceptions.JSONDecodeError as e:
|
70 |
+
logger.info(f"Error decoding JSON response from questions endpoint: {e}")
|
71 |
+
logger.info(f"Response text: {response.text[:500]}")
|
72 |
return f"Error decoding server response for questions: {e}", None
|
73 |
except Exception as e:
|
74 |
+
logger.info(f"An unexpected error occurred fetching questions: {e}")
|
75 |
return f"An unexpected error occurred fetching questions: {e}", None
|
76 |
|
77 |
# 3. Run your Agent
|
78 |
results_log = []
|
79 |
answers_payload = []
|
80 |
+
logger.info(f"Running agent on {len(questions_data)} questions...")
|
81 |
for item in questions_data:
|
82 |
task_id = item.get("task_id")
|
83 |
question_text = item.get("question")
|
84 |
if not task_id or question_text is None:
|
85 |
+
logger.info(f"Skipping item with missing task_id or question: {item}")
|
86 |
continue
|
87 |
try:
|
88 |
submitted_answer = agent(question_text)
|
89 |
answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
|
90 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
|
91 |
except Exception as e:
|
92 |
+
logger.info(f"Error running agent on task {task_id}: {e}")
|
93 |
results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
|
94 |
|
95 |
if not answers_payload:
|
96 |
+
logger.info("Agent did not produce any answers to submit.")
|
97 |
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
98 |
|
99 |
# 4. Prepare Submission
|
100 |
submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
|
101 |
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
102 |
+
logger.info(status_update)
|
103 |
|
104 |
# 5. Submit
|
105 |
+
logger.info(f"Submitting {len(answers_payload)} answers to: {submit_url}")
|
106 |
try:
|
107 |
response = requests.post(submit_url, json=submission_data, timeout=60)
|
108 |
response.raise_for_status()
|
|
|
114 |
f"({result_data.get('correct_count', '?')}/{result_data.get('total_attempted', '?')} correct)\n"
|
115 |
f"Message: {result_data.get('message', 'No message received.')}"
|
116 |
)
|
117 |
+
logger.info("Submission successful.")
|
118 |
results_df = pd.DataFrame(results_log)
|
119 |
return final_status, results_df
|
120 |
except requests.exceptions.HTTPError as e:
|
|
|
125 |
except requests.exceptions.JSONDecodeError:
|
126 |
error_detail += f" Response: {e.response.text[:500]}"
|
127 |
status_message = f"Submission Failed: {error_detail}"
|
128 |
+
logger.info(status_message)
|
129 |
results_df = pd.DataFrame(results_log)
|
130 |
return status_message, results_df
|
131 |
except requests.exceptions.Timeout:
|
132 |
status_message = "Submission Failed: The request timed out."
|
133 |
+
logger.info(status_message)
|
134 |
results_df = pd.DataFrame(results_log)
|
135 |
return status_message, results_df
|
136 |
except requests.exceptions.RequestException as e:
|
137 |
status_message = f"Submission Failed: Network error - {e}"
|
138 |
+
logger.info(status_message)
|
139 |
results_df = pd.DataFrame(results_log)
|
140 |
return status_message, results_df
|
141 |
except Exception as e:
|
142 |
status_message = f"An unexpected error occurred during submission: {e}"
|
143 |
+
logger.info(status_message)
|
144 |
results_df = pd.DataFrame(results_log)
|
145 |
return status_message, results_df
|
146 |
|
|
|
177 |
)
|
178 |
|
179 |
if __name__ == "__main__":
|
180 |
+
logger.info("\n" + "-"*30 + " App Starting " + "-"*30)
|
181 |
# Check for SPACE_HOST and SPACE_ID at startup for information
|
182 |
space_host_startup = os.getenv("SPACE_HOST")
|
183 |
space_id_startup = os.getenv("SPACE_ID") # Get SPACE_ID at startup
|
184 |
|
185 |
if space_host_startup:
|
186 |
+
logger.info(f"✅ SPACE_HOST found: {space_host_startup}")
|
187 |
+
logger.info(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
188 |
else:
|
189 |
+
logger.info("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
190 |
|
191 |
+
if space_id_startup: # logger.info repo URLs if SPACE_ID is found
|
192 |
+
logger.info(f"✅ SPACE_ID found: {space_id_startup}")
|
193 |
+
logger.info(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
194 |
+
logger.info(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
195 |
else:
|
196 |
+
logger.info("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
197 |
|
198 |
+
logger.info("-"*(60 + len(" App Starting ")) + "\n")
|
199 |
|
200 |
+
logger.info("Launching Gradio Interface for Basic Agent Evaluation...")
|
201 |
demo.launch(debug=True, share=False)
|