polyMoe commited on
Commit
f8999dc
·
verified ·
1 Parent(s): 98d55d6

Update app.py

Browse files

implémentation des caches :
- cache des questions déjà récupérées
- cache des réponses déjà obtenues

Files changed (1) hide show
  1. app.py +104 -27
app.py CHANGED
@@ -3,6 +3,7 @@ import gradio as gr
3
  import requests
4
  import inspect
5
  import pandas as pd
 
6
 
7
  # (Keep Constants as is)
8
  # --- Constants ---
@@ -48,44 +49,120 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
48
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
49
  print(agent_code)
50
 
51
- # 2. Fetch Questions
52
- print(f"Fetching questions from: {questions_url}")
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
- print("Fetched questions list is empty.")
59
- return "Fetched questions list is empty or invalid format.", None
60
- print(f"Fetched {len(questions_data)} questions.")
61
- except requests.exceptions.RequestException as e:
62
- print(f"Error fetching questions: {e}")
63
- return f"Error fetching questions: {e}", None
64
- except requests.exceptions.JSONDecodeError as e:
65
- print(f"Error decoding JSON response from questions endpoint: {e}")
66
- print(f"Response text: {response.text[:500]}")
67
- return f"Error decoding server response for questions: {e}", None
68
- except Exception as e:
69
- print(f"An unexpected error occurred fetching questions: {e}")
70
- return f"An unexpected error occurred fetching questions: {e}", None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
71
 
72
- # 3. Run your Agent
73
  results_log = []
74
  answers_payload = []
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
75
  print(f"Running agent on {len(questions_data)} questions...")
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
  print(f"Skipping item with missing task_id or question: {item}")
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
- print(f"Error running agent on task {task_id}: {e}")
88
- results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
89
 
90
  if not answers_payload:
91
  print("Agent did not produce any answers to submit.")
 
3
  import requests
4
  import inspect
5
  import pandas as pd
6
+ import json
7
 
8
  # (Keep Constants as is)
9
  # --- Constants ---
 
49
  agent_code = f"https://huggingface.co/spaces/{space_id}/tree/main"
50
  print(agent_code)
51
 
52
+ # 2. Load Questions (cache first, API fallback)
53
+ cache_path = os.path.join(os.path.dirname(__file__), "cached_questions.json")
54
+ questions_data = None
55
+
56
+ # 2.a Try cache first
57
+ if os.path.exists(cache_path):
58
+ try:
59
+ with open(cache_path, "r", encoding="utf-8") as f:
60
+ cached = json.load(f)
61
+ if isinstance(cached, list) and cached:
62
+ questions_data = cached
63
+ print(f"Loaded {len(questions_data)} questions from cache: {cache_path}")
64
+ else:
65
+ print(f"Cache file found but empty/invalid format: {cache_path}")
66
+ except json.JSONDecodeError as e:
67
+ print(f"Cache JSON is invalid ({cache_path}): {e}. Falling back to API.")
68
+ except OSError as e:
69
+ print(f"Could not read cache file ({cache_path}): {e}. Falling back to API.")
70
+
71
+ # 2.b Fetch from API only if cache missing/invalid/empty
72
+ if questions_data is None:
73
+ print(f"Fetching questions from: {questions_url}")
74
+ try:
75
+ response = requests.get(questions_url, timeout=15)
76
+ response.raise_for_status()
77
+ questions_data = response.json()
78
+
79
+ if not isinstance(questions_data, list) or not questions_data:
80
+ print("Fetched questions list is empty or invalid format.")
81
+ return "Fetched questions list is empty or invalid format.", None
82
+
83
+ print(f"Fetched {len(questions_data)} questions from API.")
84
+
85
+ # Save cache for next runs
86
+ try:
87
+ with open(cache_path, "w", encoding="utf-8") as f:
88
+ json.dump(questions_data, f, ensure_ascii=False, indent=2)
89
+ print(f"Questions cached to: {cache_path}")
90
+ except OSError as e:
91
+ print(f"Warning: unable to write cache file ({cache_path}): {e}")
92
+
93
+ except requests.exceptions.RequestException as e:
94
+ print(f"Error fetching questions: {e}")
95
+ return f"Error fetching questions: {e}", None
96
+ except requests.exceptions.JSONDecodeError as e:
97
+ print(f"Error decoding JSON response from questions endpoint: {e}")
98
+ print(f"Response text: {response.text[:500]}")
99
+ return f"Error decoding server response for questions: {e}", None
100
+ except Exception as e:
101
+ print(f"An unexpected error occurred fetching questions: {e}")
102
+ return f"An unexpected error occurred fetching questions: {e}", None
103
 
104
+ # 3. Run your Agent (answers cache by task_id)
105
  results_log = []
106
  answers_payload = []
107
+
108
+ answers_cache_path = os.path.join(os.path.dirname(__file__), "cached_answers.json")
109
+ answers_cache = {}
110
+
111
+ # 3.a Load answers cache
112
+ if os.path.exists(answers_cache_path):
113
+ try:
114
+ with open(answers_cache_path, "r", encoding="utf-8") as f:
115
+ loaded_cache = json.load(f)
116
+ if isinstance(loaded_cache, dict):
117
+ answers_cache = loaded_cache
118
+ print(f"Loaded {len(answers_cache)} cached answers from: {answers_cache_path}")
119
+ else:
120
+ print(f"Answers cache has invalid format (expected object): {answers_cache_path}")
121
+ except json.JSONDecodeError as e:
122
+ print(f"Answers cache JSON is invalid ({answers_cache_path}): {e}. Starting with empty cache.")
123
+ except OSError as e:
124
+ print(f"Could not read answers cache ({answers_cache_path}): {e}. Starting with empty cache.")
125
+
126
+ cache_updated = False
127
+
128
  print(f"Running agent on {len(questions_data)} questions...")
129
  for item in questions_data:
130
  task_id = item.get("task_id")
131
  question_text = item.get("question")
132
+
133
  if not task_id or question_text is None:
134
  print(f"Skipping item with missing task_id or question: {item}")
135
  continue
136
+
137
+ task_key = str(task_id)
138
+
139
+ # Use cached answer if available
140
+ if task_key in answers_cache:
141
+ submitted_answer = answers_cache[task_key]
142
+ print(f"Using cached answer for task_id={task_id}")
143
+ else:
144
+ try:
145
+ submitted_answer = agent(question_text)
146
+ answers_cache[task_key] = submitted_answer
147
+ cache_updated = True
148
+ print(f"Computed and cached answer for task_id={task_id}")
149
+ except Exception as e:
150
+ print(f"Error running agent on task {task_id}: {e}")
151
+ results_log.append(
152
+ {"Task ID": task_id, "Question": question_text, "Submitted Answer": f"AGENT ERROR: {e}"})
153
+ continue
154
+
155
+ answers_payload.append({"task_id": task_id, "submitted_answer": submitted_answer})
156
+ results_log.append({"Task ID": task_id, "Question": question_text, "Submitted Answer": submitted_answer})
157
+
158
+ # 3.b Save answers cache only if updated
159
+ if cache_updated:
160
  try:
161
+ with open(answers_cache_path, "w", encoding="utf-8") as f:
162
+ json.dump(answers_cache, f, ensure_ascii=False, indent=2)
163
+ print(f"Answers cache updated: {answers_cache_path}")
164
+ except OSError as e:
165
+ print(f"Warning: unable to write answers cache ({answers_cache_path}): {e}")
 
166
 
167
  if not answers_payload:
168
  print("Agent did not produce any answers to submit.")