Spaces:
Sleeping
Sleeping
File size: 7,289 Bytes
9281fab |
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 |
"""
Gradio Web Interface for CoDA.
Provides a user-friendly web UI for the CoDA visualization system,
designed for deployment on Hugging Face Spaces.
"""
import logging
import os
import tempfile
from pathlib import Path
from typing import Optional
import gradio as gr
logging.basicConfig(
level=logging.INFO,
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s"
)
logger = logging.getLogger(__name__)
def create_coda_interface():
"""Create the Gradio interface for CoDA."""
def process_visualization(
query: str,
data_file,
progress=gr.Progress()
) -> tuple[Optional[str], str, str]:
"""
Process a visualization request.
Args:
query: Natural language visualization query
data_file: Uploaded data file
progress: Gradio progress tracker
Returns:
Tuple of (image_path, status_message, details)
"""
if not query.strip():
return None, "β Error", "Please enter a visualization query."
if data_file is None:
return None, "β Error", "Please upload a data file."
try:
from coda.config import Config
from coda.orchestrator import CodaOrchestrator
except ImportError as e:
return None, "β Import Error", f"Failed to import CoDA: {e}"
groq_api_key = os.getenv("GROQ_API_KEY", "")
if not groq_api_key:
return (
None,
"β Configuration Error",
"GROQ_API_KEY environment variable is not set. "
"Please add your API key in the Spaces settings."
)
with tempfile.TemporaryDirectory() as temp_dir:
data_path = Path(temp_dir) / Path(data_file.name).name
with open(data_file.name, 'rb') as src:
with open(data_path, 'wb') as dst:
dst.write(src.read())
def update_progress(status: str, pct: float):
progress(pct, desc=status)
try:
config = Config(
groq_api_key=groq_api_key,
)
orchestrator = CodaOrchestrator(
config=config,
progress_callback=update_progress,
)
result = orchestrator.run(
query=query,
data_paths=[str(data_path)],
)
if result.success and result.output_file:
scores = result.scores or {}
details = format_results(result, scores)
return result.output_file, "β
Success", details
else:
error_msg = result.error or "Unknown error occurred"
return None, "β Failed", f"Visualization failed: {error_msg}"
except Exception as e:
logger.exception("Pipeline error")
return None, "β Error", f"An error occurred: {str(e)}"
def format_results(result, scores: dict) -> str:
"""Format the results for display."""
lines = [
f"**Iterations:** {result.iterations}",
"",
"### Quality Scores",
]
if scores:
for key, value in scores.items():
emoji = "π’" if value >= 7 else "π‘" if value >= 5 else "π΄"
lines.append(f"- {key.title()}: {emoji} {value:.1f}/10")
if result.evaluation:
if result.evaluation.strengths:
lines.extend(["", "### Strengths"])
for s in result.evaluation.strengths[:3]:
lines.append(f"- {s}")
if result.evaluation.recommendations:
lines.extend(["", "### Recommendations"])
for r in result.evaluation.recommendations[:3]:
lines.append(f"- {r}")
return "\n".join(lines)
with gr.Blocks(
title="CoDA - Collaborative Data Visualization",
theme=gr.themes.Soft(),
css="""
.main-title {
text-align: center;
margin-bottom: 1rem;
}
.status-box {
padding: 1rem;
border-radius: 8px;
margin-top: 1rem;
}
"""
) as interface:
gr.Markdown(
"""
# π¨ CoDA: Collaborative Data Visualization Agents
Transform your data into beautiful visualizations using natural language.
Simply upload your data and describe what you want to see!
""",
elem_classes=["main-title"]
)
with gr.Row():
with gr.Column(scale=1):
query_input = gr.Textbox(
label="Visualization Query",
placeholder="e.g., 'Create a line chart showing sales trends over time'",
lines=3,
)
file_input = gr.File(
label="Upload Data File",
file_types=[".csv", ".json", ".xlsx", ".xls", ".parquet"],
)
submit_btn = gr.Button(
"π Generate Visualization",
variant="primary",
size="lg",
)
gr.Markdown(
"""
### Supported Formats
- CSV, JSON, Excel (.xlsx, .xls), Parquet
### Example Queries
- "Show me a bar chart of sales by category"
- "Create a scatter plot of price vs quantity"
- "Plot the distribution of ages as a histogram"
"""
)
with gr.Column(scale=2):
output_image = gr.Image(
label="Generated Visualization",
type="filepath",
)
with gr.Row():
status_output = gr.Textbox(
label="Status",
interactive=False,
)
details_output = gr.Markdown(
label="Details",
)
gr.Examples(
examples=[
["Create a bar chart showing the top 10 values", None],
["Plot a line chart of trends over time", None],
["Show a scatter plot with correlation", None],
["Create a pie chart of category distribution", None],
],
inputs=[query_input, file_input],
)
submit_btn.click(
fn=process_visualization,
inputs=[query_input, file_input],
outputs=[output_image, status_output, details_output],
)
return interface
app = create_coda_interface()
if __name__ == "__main__":
app.launch()
|