Jofthomas commited on
Commit
b177367
·
verified ·
1 Parent(s): 7d65c66

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +7 -60
app.py CHANGED
@@ -10,7 +10,6 @@ DEFAULT_API_URL = "https://jofthomas-unit4-scoring.hf.space/"
10
 
11
  # --- Basic Agent Definition ---
12
  class BasicAgent:
13
- # ... (keep agent code as is) ...
14
  def __init__(self):
15
  print("BasicAgent initialized.")
16
  def __call__(self, question: str) -> str:
@@ -18,34 +17,6 @@ class BasicAgent:
18
  fixed_answer = "This is a default answer."
19
  print(f"Agent returning fixed answer: {fixed_answer}")
20
  return fixed_answer
21
- def __repr__(self) -> str:
22
- imports = ["import inspect\n"]
23
- try:
24
- class_source = inspect.getsource(BasicAgent)
25
- full_source = "\n".join(imports) + "\n" + class_source
26
- return full_source
27
- except Exception as e:
28
- print(f"Error getting source code via inspect: {e}")
29
- return f"# Could not get source via inspect: {e}"
30
-
31
- # --- Gradio UI and Logic ---
32
- def get_current_script_content() -> str:
33
- # ... (keep function as is) ...
34
- try:
35
- script_path = os.path.abspath(__file__)
36
- print(f"Reading script content from: {script_path}")
37
- with open(script_path, 'r', encoding='utf-8') as f:
38
- return f.read()
39
- except NameError:
40
- print("Warning: __file__ is not defined. Cannot read script content this way.")
41
- return "# Agent code unavailable: __file__ not defined"
42
- except FileNotFoundError:
43
- print(f"Warning: Script file '{script_path}' not found.")
44
- return f"# Agent code unavailable: Script file not found at {script_path}"
45
- except Exception as e:
46
- print(f"Error reading script file '{script_path}': {e}")
47
- return f"# Agent code unavailable: Error reading script file: {e}"
48
-
49
 
50
  def run_and_submit_all( profile: gr.OAuthProfile | None):
51
  """
@@ -53,52 +24,28 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
53
  and displays the results.
54
  """
55
  # --- Determine HF Space Runtime URL and Repo URL ---
56
- space_host = os.getenv("SPACE_HOST")
57
- space_id = os.getenv("SPACE_ID") # Get the SPACE_ID
58
-
59
- hf_runtime_url = "Runtime: Locally or unknown environment (SPACE_HOST not found)"
60
- hf_repo_url = "HF Repo URL: Unknown (SPACE_ID not found)"
61
- hf_repo_tree_url = "HF Repo Tree URL: Unknown (SPACE_ID not found)"
62
-
63
- if space_host:
64
- hf_runtime_url = f"Runtime URL: https://{space_host}.hf.space"
65
-
66
- if space_id: # Construct URLs using SPACE_ID
67
- hf_repo_url = f"HF Repo URL: https://huggingface.co/spaces/{space_id}"
68
- hf_repo_tree_url = f"HF Repo Tree URL: https://huggingface.co/spaces/{space_id}/tree/main"
69
-
70
- # Print runtime and repo info at the start
71
- print("\n" + "="*60)
72
- print("Executing run_and_submit_all function...")
73
- print(hf_runtime_url) # Print the runtime URL (from SPACE_HOST)
74
- print(hf_repo_url) # Print the base repo URL (from SPACE_ID)
75
- print(hf_repo_tree_url) # Print the repo tree URL (from SPACE_ID)
76
- # --- End Environment Info ---
77
 
78
  if profile:
79
  username= f"{profile.username}"
80
  print(f"User logged in: {username}")
81
  else:
82
  print("User not logged in.")
83
- print("="*60 + "\n")
84
  return "Please Login to Hugging Face with the button.", None
85
 
86
- print("="*60 + "\n")
87
-
88
- # ... (rest of the function remains the same) ...
89
  api_url = DEFAULT_API_URL
90
  questions_url = f"{api_url}/questions"
91
  submit_url = f"{api_url}/submit"
92
 
93
- # 1. Instantiate Agent
94
  try:
95
  agent = BasicAgent()
96
  except Exception as e:
97
  print(f"Error instantiating agent: {e}")
98
  return f"Error initializing agent: {e}", None
99
- agent_code = get_current_script_content()
100
- if agent_code.startswith("# Agent code unavailable"):
101
- print("Warning: Using potentially incomplete agent code due to reading error.")
102
 
103
  # 2. Fetch Questions
104
  print(f"Fetching questions from: {questions_url}")
@@ -121,7 +68,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
121
  print(f"An unexpected error occurred fetching questions: {e}")
122
  return f"An unexpected error occurred fetching questions: {e}", None
123
 
124
- # 3. Run Agent
125
  results_log = []
126
  answers_payload = []
127
  print(f"Running agent on {len(questions_data)} questions...")
@@ -143,7 +90,7 @@ def run_and_submit_all( profile: gr.OAuthProfile | None):
143
  print("Agent did not produce any answers to submit.")
144
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
145
 
146
- # 4. Prepare Submission
147
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
148
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
149
  print(status_update)
 
10
 
11
  # --- Basic Agent Definition ---
12
  class BasicAgent:
 
13
  def __init__(self):
14
  print("BasicAgent initialized.")
15
  def __call__(self, question: str) -> str:
 
17
  fixed_answer = "This is a default answer."
18
  print(f"Agent returning fixed answer: {fixed_answer}")
19
  return fixed_answer
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
 
21
  def run_and_submit_all( profile: gr.OAuthProfile | None):
22
  """
 
24
  and displays the results.
25
  """
26
  # --- Determine HF Space Runtime URL and Repo URL ---
27
+ space_id = os.getenv("SPACE_ID") # Get the SPACE_ID for sending link to the code
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
28
 
29
  if profile:
30
  username= f"{profile.username}"
31
  print(f"User logged in: {username}")
32
  else:
33
  print("User not logged in.")
 
34
  return "Please Login to Hugging Face with the button.", None
35
 
 
 
 
36
  api_url = DEFAULT_API_URL
37
  questions_url = f"{api_url}/questions"
38
  submit_url = f"{api_url}/submit"
39
 
40
+ # 1. Instantiate Agent ( modify this part to create your agent)
41
  try:
42
  agent = BasicAgent()
43
  except Exception as e:
44
  print(f"Error instantiating agent: {e}")
45
  return f"Error initializing agent: {e}", None
46
+ # 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)
47
+ agent_code = "https://huggingface.co/spaces/{space_id}/tree/main"
48
+
49
 
50
  # 2. Fetch Questions
51
  print(f"Fetching questions from: {questions_url}")
 
68
  print(f"An unexpected error occurred fetching questions: {e}")
69
  return f"An unexpected error occurred fetching questions: {e}", None
70
 
71
+ # 3. Run your Agent
72
  results_log = []
73
  answers_payload = []
74
  print(f"Running agent on {len(questions_data)} questions...")
 
90
  print("Agent did not produce any answers to submit.")
91
  return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
92
 
93
+ # 4. Prepare Submission
94
  submission_data = {"username": username.strip(), "agent_code": agent_code, "answers": answers_payload}
95
  status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
96
  print(status_update)