Spaces:
Runtime error
Runtime error
import pandas as pd | |
import matplotlib.pyplot as plt | |
import seaborn as sns | |
from fastapi import FastAPI, UploadFile, File, HTTPException | |
import io | |
from transformers import pipeline | |
# Initialize FastAPI app | |
app = FastAPI() | |
# Load Hugging Face model for text-to-code generation | |
generator = pipeline("text-generation", model="Salesforce/codegen-350M-mono") | |
def generate_viz_code(prompt: str) -> str: | |
"""Generate Python code for visualization based on user prompt.""" | |
response = generator(prompt, max_length=200) | |
return response[0]["generated_text"] | |
def visualize_data(file: UploadFile = File(...), prompt: str = ""): | |
try: | |
# Ensure the file is an Excel file | |
if not file.filename.endswith(('.xls', '.xlsx')): | |
raise HTTPException(status_code=400, detail="Only Excel files (.xls, .xlsx) are supported.") | |
# Read the uploaded Excel file | |
contents = file.file.read() | |
df = pd.read_excel(io.BytesIO(contents)) | |
# Generate visualization code | |
code = generate_viz_code(prompt) | |
print("Generated Code:\n", code) # Debug output | |
# Execute the generated code | |
exec_globals = {"plt": plt, "sns": sns, "pd": pd, "df": df} | |
exec(code, exec_globals) | |
# Save the generated plot | |
img_path = "visualization.png" | |
plt.savefig(img_path) | |
plt.close() | |
return {"image_path": img_path} | |
except Exception as e: | |
return {"error": str(e)} | |
# Uncomment below to run standalone FastAPI app | |
# if __name__ == "__main__": | |
# import uvicorn | |
# uvicorn.run(app, host="0.0.0.0", port=8000) | |