Spaces:
Sleeping
Sleeping
File size: 13,436 Bytes
ddabbe4 8d5b1f0 ddabbe4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 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 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 |
"""
Minimal Gradio app for CrewAI data analysis with file upload and parallel agent execution.
"""
import os
import gradio as gr
import traceback
from crew import create_flow_crew, create_analyst_only_crew
def process_file_and_analyze(file, user_query: str = "", engineer_result: str = None) -> tuple[str, str]:
"""
Process uploaded file and run all agents (Engineer, Analyst, Storyteller), then merge results.
Used for the "Analyze Dataset" button.
Args:
file: Uploaded file object
user_query: The user's analysis query/task (empty for general analysis)
engineer_result: Previously computed engineer result (if available)
Returns:
tuple: (merged_results, engineer_result) - engineer_result is stored for reuse
"""
if file is None:
return "Please upload a CSV file.", engineer_result or ""
# Use default analysis if no query provided
if not user_query or not user_query.strip():
user_query = "Provide a comprehensive analysis of the dataset including: top performers, key statistics, interesting patterns, and notable insights."
try:
# Get file path
file_path = file.name if hasattr(file, 'name') else str(file)
csv_path = file_path
# Full analysis: run all agents
crew = create_flow_crew(user_query.strip(), csv_path)
result = crew.kickoff()
merged_output = []
stored_engineer_result = ""
# Get engineer result (first task)
if hasattr(result, 'tasks_output') and result.tasks_output:
if len(result.tasks_output) >= 1:
engineer_output = str(result.tasks_output[0])
stored_engineer_result = engineer_output
merged_output.append("## Engineer Agent Results")
merged_output.append("")
merged_output.append(engineer_output)
merged_output.append("")
merged_output.append("---")
merged_output.append("")
# Get analyst result (second task)
if hasattr(result, 'tasks_output') and result.tasks_output:
if len(result.tasks_output) >= 2:
analyst_output = str(result.tasks_output[1])
merged_output.append("## Analyst Agent Results")
merged_output.append("")
merged_output.append(analyst_output)
merged_output.append("")
merged_output.append("---")
merged_output.append("")
# Get storyteller result (third task)
if hasattr(result, 'tasks_output') and result.tasks_output:
if len(result.tasks_output) >= 3:
storyteller_output = str(result.tasks_output[2])
merged_output.append("## Storyteller Agent Results")
merged_output.append("")
merged_output.append(storyteller_output)
merged_output.append("")
# If we couldn't extract from tasks_output, use the full result
if not merged_output:
merged_output.append("## Complete Analysis Results")
merged_output.append("")
merged_output.append(str(result))
return "\n".join(merged_output), stored_engineer_result
except Exception as e:
error_trace = traceback.format_exc()
error_msg = f"Error: {str(e)}\n\nTraceback:\n{error_trace}"
print(error_msg)
return error_msg, engineer_result or ""
def process_question_only(file, user_query: str) -> str:
"""
Process a specific user question using only the Analyst agent (no Engineer, no Storyteller).
Used for the "Analyze with Question" button.
Args:
file: Uploaded file object
user_query: The user's specific analysis question
Returns:
str: Analyst results only
"""
if file is None:
return "Please upload a CSV file."
if not user_query or not user_query.strip():
return "Please enter a question."
try:
# Get file path
file_path = file.name if hasattr(file, 'name') else str(file)
csv_path = file_path
# Run only analyst
crew = create_analyst_only_crew(user_query.strip(), csv_path)
result = crew.kickoff()
# Get analyst result
if hasattr(result, 'tasks_output') and result.tasks_output:
if len(result.tasks_output) >= 1:
analyst_output = str(result.tasks_output[0])
return analyst_output
# Fallback to full result
return str(result)
except Exception as e:
error_trace = traceback.format_exc()
error_msg = f"Error: {str(e)}\n\nTraceback:\n{error_trace}"
print(error_msg)
return error_msg
def create_app():
"""Create and return the Gradio interface."""
with gr.Blocks(title="NBA Stats Analysis with CrewAI", theme=gr.themes.Soft()) as app:
gr.Markdown("""
# NBA Stats Analysis with CrewAI
Upload your NBA statistics CSV file to get comprehensive analysis with engaging storylines.
**How it works:**
- **Engineer Agent**: Examines and validates your dataset
- **Analyst Agent**: Performs deep analysis (general or based on your question)
- **Storyteller Agent**: Creates headlines and compelling storylines
All agents work in parallel and results are merged for you!
""")
# Store engineer result in state
engineer_state = gr.State(value="")
with gr.Row():
with gr.Column(scale=1):
file_input = gr.File(
label="Upload CSV File",
file_types=[".csv"],
type="filepath"
)
analyze_btn = gr.Button(
"Analyze Dataset",
variant="primary",
size="lg",
visible=False
)
gr.Markdown("### Ask a Specific Question")
query_input = gr.Textbox(
label="Your Analysis Question",
placeholder="e.g., 'Who are the top 5 three-point shooters?' or 'Analyze the best players by assists'",
lines=2
)
question_output = gr.Markdown(
value="",
label="Answer",
visible=False
)
query_btn = gr.Button(
"Analyze with Question",
variant="secondary",
size="lg"
)
with gr.Row():
with gr.Column():
status_output = gr.Markdown(
value="",
label="Agent Status",
visible=False
)
with gr.Row():
with gr.Column():
merged_output = gr.Markdown(
value="**Ready to analyze!** Upload a CSV file above, then click 'Analyze Dataset' to get started.",
label="Full Analysis Results"
)
def show_loading_animation(is_question: bool = False):
"""Show loading animation while processing."""
if is_question:
return """## Analysis in Progress...
<div style="text-align: center; padding: 20px;">
<div style="font-size: 18px; margin-bottom: 15px;">
<strong>Analyzing your question...</strong>
</div>
<div style="display: flex; justify-content: center; max-width: 600px; margin: 0 auto;">
<div style="text-align: center; margin: 10px;">
<div style="font-size: 14px; font-weight: bold;">Analyst Agent</div>
<div style="font-size: 12px; color: #666; margin-top: 5px;">Processing query...</div>
</div>
</div>
<div style="margin-top: 25px; font-size: 14px; color: #888;">
This may take a moment... Please wait while the agent processes your question.
</div>
</div>"""
else:
return """## Analysis in Progress...
<div style="text-align: center; padding: 20px;">
<div style="font-size: 18px; margin-bottom: 15px;">
<strong>Agents are working in parallel...</strong>
</div>
<div style="display: flex; justify-content: space-around; max-width: 600px; margin: 0 auto; flex-wrap: wrap;">
<div style="text-align: center; margin: 10px;">
<div style="font-size: 14px; font-weight: bold;">Engineer Agent</div>
<div style="font-size: 12px; color: #666; margin-top: 5px;">Examining dataset...</div>
</div>
<div style="text-align: center; margin: 10px;">
<div style="font-size: 14px; font-weight: bold;">Analyst Agent</div>
<div style="font-size: 12px; color: #666; margin-top: 5px;">Analyzing data...</div>
</div>
<div style="text-align: center; margin: 10px;">
<div style="font-size: 14px; font-weight: bold;">Storyteller Agent</div>
<div style="font-size: 12px; color: #666; margin-top: 5px;">Creating storylines...</div>
</div>
</div>
<div style="margin-top: 25px; font-size: 14px; color: #888;">
This may take a moment... Please wait while the agents process your data.
</div>
</div>"""
def on_file_upload(file):
"""Handle file upload - show analyze button and reset state."""
if file is not None:
return gr.update(visible=True), ""
return gr.update(visible=False), ""
def start_full_analysis(file, engineer_result: str = ""):
"""Start full analysis and show loading animation."""
loading_msg = show_loading_animation(is_question=False)
return gr.update(visible=True, value=loading_msg), gr.update(value="")
def complete_full_analysis(file, engineer_result: str = ""):
"""Complete full analysis and return results."""
result, new_engineer_result = process_file_and_analyze(file, "", engineer_result)
if result.startswith("Error:") or result.startswith("Please upload"):
result = f"### {result}"
return result, gr.update(visible=False), new_engineer_result
def start_question_analysis(file, user_query: str = ""):
"""Start question analysis and show loading animation."""
loading_msg = show_loading_animation(is_question=True)
return gr.update(visible=True, value=loading_msg), gr.update(visible=True, value="")
def complete_question_analysis(file, user_query: str = ""):
"""Complete question analysis and return results."""
result = process_question_only(file, user_query)
if result.startswith("Error:") or result.startswith("Please"):
result = f"### {result}"
else:
# Format the answer in a highlighted box
result = f"""<div style="background-color: #f0f7ff; border: 2px solid #4a90e2; border-radius: 8px; padding: 15px; margin: 10px 0;">
{result}
</div>"""
return result, gr.update(visible=False)
# When file is uploaded, show analyze button and reset engineer state
file_input.change(
fn=on_file_upload,
inputs=[file_input],
outputs=[analyze_btn, engineer_state]
)
# Analyze button - runs general analysis (no query needed)
analyze_btn.click(
fn=start_full_analysis,
inputs=[file_input, engineer_state],
outputs=[status_output, merged_output]
).then(
fn=complete_full_analysis,
inputs=[file_input, engineer_state],
outputs=[merged_output, status_output, engineer_state]
)
# Query button - runs analysis with user's question (only Analyst)
query_btn.click(
fn=start_question_analysis,
inputs=[file_input, query_input],
outputs=[status_output, question_output]
).then(
fn=complete_question_analysis,
inputs=[file_input, query_input],
outputs=[question_output, status_output]
)
# Allow Enter key to submit query
query_input.submit(
fn=start_question_analysis,
inputs=[file_input, query_input],
outputs=[status_output, question_output]
).then(
fn=complete_question_analysis,
inputs=[file_input, query_input],
outputs=[question_output, status_output]
)
return app
if __name__ == "__main__":
try:
print("Creating Gradio app...")
app = create_app()
print("Launching Gradio app...")
# For Hugging Face Spaces, use default launch settings
# Spaces will automatically handle server_name and port
app.launch(
show_error=True
)
except Exception as e:
print(f"Error launching app: {e}")
traceback.print_exc()
raise
|