Update app.py
Browse files
app.py
CHANGED
|
@@ -1,196 +1,144 @@
|
|
| 1 |
-
import os
|
| 2 |
import gradio as gr
|
| 3 |
-
import
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
class BasicAgent:
|
| 14 |
-
def __init__(self):
|
| 15 |
-
print("BasicAgent initialized.")
|
| 16 |
-
def __call__(self, question: str) -> str:
|
| 17 |
-
print(f"Agent received question (first 50 chars): {question[:50]}...")
|
| 18 |
-
fixed_answer = "This is a default answer."
|
| 19 |
-
print(f"Agent returning fixed answer: {fixed_answer}")
|
| 20 |
-
return fixed_answer
|
| 21 |
-
|
| 22 |
-
def run_and_submit_all( profile: gr.OAuthProfile | None):
|
| 23 |
"""
|
| 24 |
-
|
| 25 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
"""
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
else:
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
|
| 41 |
-
|
| 42 |
-
|
| 43 |
-
|
| 44 |
-
except Exception as e:
|
| 45 |
-
print(f"Error instantiating agent: {e}")
|
| 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 |
-
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.")
|
| 92 |
-
return "Agent did not produce any answers to submit.", pd.DataFrame(results_log)
|
| 93 |
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
status_update = f"Agent finished. Submitting {len(answers_payload)} answers for user '{username}'..."
|
| 97 |
-
print(status_update)
|
| 98 |
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
|
| 102 |
-
|
| 103 |
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 111 |
)
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
except Exception as e:
|
| 137 |
-
status_message = f"An unexpected error occurred during submission: {e}"
|
| 138 |
-
print(status_message)
|
| 139 |
-
results_df = pd.DataFrame(results_log)
|
| 140 |
-
return status_message, results_df
|
| 141 |
-
|
| 142 |
-
|
| 143 |
-
# --- Build Gradio Interface using Blocks ---
|
| 144 |
-
with gr.Blocks() as demo:
|
| 145 |
-
gr.Markdown("# Basic Agent Evaluation Runner")
|
| 146 |
-
gr.Markdown(
|
| 147 |
-
"""
|
| 148 |
-
**Instructions:**
|
| 149 |
-
|
| 150 |
-
1. Please clone this space, then modify the code to define your agent's logic, the tools, the necessary packages, etc ...
|
| 151 |
-
2. Log in to your Hugging Face account using the button below. This uses your HF username for submission.
|
| 152 |
-
3. Click 'Run Evaluation & Submit All Answers' to fetch questions, run your agent, submit answers, and see the score.
|
| 153 |
-
|
| 154 |
-
---
|
| 155 |
-
**Disclaimers:**
|
| 156 |
-
Once clicking on the "submit button, it can take quite some time ( this is the time for the agent to go through all the questions).
|
| 157 |
-
This space provides a basic setup and is intentionally sub-optimal to encourage you to develop your own, more robust solution. For instance for the delay process of the submit button, a solution could be to cache the answers and submit in a seperate action or even to answer the questions in async.
|
| 158 |
-
"""
|
| 159 |
-
)
|
| 160 |
-
|
| 161 |
-
gr.LoginButton()
|
| 162 |
-
|
| 163 |
-
run_button = gr.Button("Run Evaluation & Submit All Answers")
|
| 164 |
-
|
| 165 |
-
status_output = gr.Textbox(label="Run Status / Submission Result", lines=5, interactive=False)
|
| 166 |
-
# Removed max_rows=10 from DataFrame constructor
|
| 167 |
-
results_table = gr.DataFrame(label="Questions and Agent Answers", wrap=True)
|
| 168 |
-
|
| 169 |
-
run_button.click(
|
| 170 |
-
fn=run_and_submit_all,
|
| 171 |
-
outputs=[status_output, results_table]
|
| 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 |
-
print(f"✅ SPACE_HOST found: {space_host_startup}")
|
| 182 |
-
print(f" Runtime URL should be: https://{space_host_startup}.hf.space")
|
| 183 |
-
else:
|
| 184 |
-
print("ℹ️ SPACE_HOST environment variable not found (running locally?).")
|
| 185 |
-
|
| 186 |
-
if space_id_startup: # Print repo URLs if SPACE_ID is found
|
| 187 |
-
print(f"✅ SPACE_ID found: {space_id_startup}")
|
| 188 |
-
print(f" Repo URL: https://huggingface.co/spaces/{space_id_startup}")
|
| 189 |
-
print(f" Repo Tree URL: https://huggingface.co/spaces/{space_id_startup}/tree/main")
|
| 190 |
-
else:
|
| 191 |
-
print("ℹ️ SPACE_ID environment variable not found (running locally?). Repo URL cannot be determined.")
|
| 192 |
-
|
| 193 |
-
print("-"*(60 + len(" App Starting ")) + "\n")
|
| 194 |
-
|
| 195 |
-
print("Launching Gradio Interface for Basic Agent Evaluation...")
|
| 196 |
-
demo.launch(debug=True, share=False)
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
from textblob import TextBlob
|
| 3 |
+
|
| 4 |
+
def analyze_text(text: str) -> str:
|
| 5 |
+
"""Analyze text and return statistics.
|
| 6 |
+
|
| 7 |
+
Args:
|
| 8 |
+
text: The input text to analyze
|
| 9 |
+
|
| 10 |
+
Returns:
|
| 11 |
+
JSON string with analysis results
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 12 |
"""
|
| 13 |
+
words = text.split()
|
| 14 |
+
chars = len(text)
|
| 15 |
+
chars_no_spaces = len(text.replace(" ", ""))
|
| 16 |
+
sentences = text.count(".") + text.count("!") + text.count("?")
|
| 17 |
+
|
| 18 |
+
avg_word_length = round(chars_no_spaces / len(words), 2) if words else 0
|
| 19 |
+
avg_sentence_length = round(len(words) / max(sentences, 1), 2)
|
| 20 |
+
|
| 21 |
+
return json.dumps({
|
| 22 |
+
"total_characters": chars,
|
| 23 |
+
"characters_without_spaces": chars_no_spaces,
|
| 24 |
+
"total_words": len(words),
|
| 25 |
+
"total_sentences": max(sentences, 1),
|
| 26 |
+
"average_word_length": avg_word_length,
|
| 27 |
+
"average_sentence_length": avg_sentence_length
|
| 28 |
+
}, indent=2)
|
| 29 |
+
|
| 30 |
+
def extract_keywords(text: str, count: int = 5) -> str:
|
| 31 |
+
"""Extract keywords (most common words) from text.
|
| 32 |
+
|
| 33 |
+
Args:
|
| 34 |
+
text: The input text
|
| 35 |
+
count: Number of keywords to return (default 5)
|
| 36 |
+
|
| 37 |
+
Returns:
|
| 38 |
+
JSON string with keywords and frequencies
|
| 39 |
"""
|
| 40 |
+
stopwords = {
|
| 41 |
+
"the", "a", "an", "and", "or", "but", "in", "on", "at", "to", "for",
|
| 42 |
+
"of", "with", "is", "are", "was", "were", "be", "been", "by", "from"
|
| 43 |
+
}
|
| 44 |
+
|
| 45 |
+
words = text.lower().split()
|
| 46 |
+
filtered = [w.strip(".,!?;:") for w in words if w.lower() not in stopwords]
|
| 47 |
+
|
| 48 |
+
from collections import Counter
|
| 49 |
+
word_freq = Counter(filtered)
|
| 50 |
+
top_words = word_freq.most_common(count)
|
| 51 |
+
|
| 52 |
+
return json.dumps({
|
| 53 |
+
"keywords": [{"word": w, "frequency": f} for w, f in top_words]
|
| 54 |
+
}, indent=2)
|
| 55 |
+
|
| 56 |
+
def check_reading_level(text: str) -> str:
|
| 57 |
+
"""Estimate reading difficulty level.
|
| 58 |
+
|
| 59 |
+
Args:
|
| 60 |
+
text: The input text
|
| 61 |
+
|
| 62 |
+
Returns:
|
| 63 |
+
JSON string with reading level estimate
|
| 64 |
+
"""
|
| 65 |
+
sentences = max(text.count(".") + text.count("!") + text.count("?"), 1)
|
| 66 |
+
words = len(text.split())
|
| 67 |
+
vowels = "aeiou"
|
| 68 |
+
syllables = sum(1 for c in text.lower() if c in vowels)
|
| 69 |
+
|
| 70 |
+
if words == 0:
|
| 71 |
+
return json.dumps({"error": "No text to analyze"})
|
| 72 |
+
|
| 73 |
+
grade = max(0, (0.39 * (words / sentences)) + (11.8 * (syllables / words)) - 15.59)
|
| 74 |
+
|
| 75 |
+
if grade < 6:
|
| 76 |
+
level = "Elementary School"
|
| 77 |
+
elif grade < 9:
|
| 78 |
+
level = "Middle School"
|
| 79 |
+
elif grade < 13:
|
| 80 |
+
level = "High School"
|
| 81 |
else:
|
| 82 |
+
level = "College/Academic"
|
| 83 |
+
|
| 84 |
+
return json.dumps({
|
| 85 |
+
"grade_level": round(grade, 1),
|
| 86 |
+
"reading_level": level
|
| 87 |
+
}, indent=2)
|
| 88 |
+
|
| 89 |
+
def sentiment_analysis(text: str) -> dict:
|
| 90 |
+
"""
|
| 91 |
+
Analyze the sentiment of the given text.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
|
| 93 |
+
Args:
|
| 94 |
+
text (str): The text to analyze
|
|
|
|
|
|
|
| 95 |
|
| 96 |
+
Returns:
|
| 97 |
+
dict: A dictionary containing polarity, subjectivity, and assessment
|
| 98 |
+
"""
|
| 99 |
+
blob = TextBlob(text)
|
| 100 |
+
sentiment = blob.sentiment
|
| 101 |
+
|
| 102 |
+
return {
|
| 103 |
+
"polarity": round(sentiment.polarity, 2), # -1 (negative) to 1 (positive)
|
| 104 |
+
"subjectivity": round(sentiment.subjectivity, 2), # 0 (objective) to 1 (subjective)
|
| 105 |
+
"assessment": "positive" if sentiment.polarity > 0 else "negative" if sentiment.polarity < 0 else "neutral"
|
| 106 |
+
}
|
| 107 |
+
|
| 108 |
+
# Create web UI
|
| 109 |
+
with gr.Blocks(title="Text Processor") as demo:
|
| 110 |
+
gr.Markdown("# Text Processing Tools")
|
| 111 |
+
gr.Markdown("Analyze text statistics, extract keywords, and check reading difficulty.")
|
| 112 |
+
|
| 113 |
+
with gr.Tab("Analyze Text"):
|
| 114 |
+
text_input1 = gr.Textbox(
|
| 115 |
+
label="Enter text",
|
| 116 |
+
lines=8,
|
| 117 |
+
placeholder="Paste your text here..."
|
| 118 |
)
|
| 119 |
+
analysis_output = gr.Textbox(label="Analysis Results", lines=8)
|
| 120 |
+
gr.Button("Analyze", size="lg").click(analyze_text, text_input1, analysis_output)
|
| 121 |
+
|
| 122 |
+
with gr.Tab("Extract Keywords"):
|
| 123 |
+
text_input2 = gr.Textbox(label="Enter text", lines=8)
|
| 124 |
+
count_input = gr.Slider(1, 20, value=5, step=1, label="Number of keywords")
|
| 125 |
+
keywords_output = gr.Textbox(label="Keywords", lines=8)
|
| 126 |
+
gr.Button("Extract", size="lg").click(
|
| 127 |
+
extract_keywords,
|
| 128 |
+
[text_input2, count_input],
|
| 129 |
+
keywords_output
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
with gr.Tab("Reading Level"):
|
| 133 |
+
text_input3 = gr.Textbox(label="Enter text", lines=8)
|
| 134 |
+
level_output = gr.Textbox(label="Reading Level Analysis", lines=5)
|
| 135 |
+
gr.Button("Check Level", size="lg").click(check_reading_level, text_input3, level_output)
|
| 136 |
+
|
| 137 |
+
with gr.Tab("Text Sentiment Analysis"):
|
| 138 |
+
text_input4 = gr.Textbox(label="Enter text", lines=8, placeholder="Enter text to analyze...")
|
| 139 |
+
sentiment_output = gr.Textbox(label="Text Sentiment Analysis", lines=5)
|
| 140 |
+
gr.Button("Check Level", size="lg").click(sentiment_analysis, text_input4, sentiment_output)
|
| 141 |
+
|
| 142 |
+
# Launch the interface and MCP server
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 143 |
if __name__ == "__main__":
|
| 144 |
+
demo.launch(mcp_server=True)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|