Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, BackgroundTasks | |
| from fastapi.responses import FileResponse | |
| from pydantic import BaseModel | |
| import os | |
| from datetime import datetime | |
| # This imports the functions from your massive script (which we will upload next) | |
| from report_generator import ( | |
| calculate_metrics, get_ai_analysis, chart_daily_completion, | |
| chart_goal_proximity_gauge, chart_dow_performance, | |
| chart_score_breakdown, build_pdf | |
| ) | |
| app = FastAPI(title="FocusDesk AI Analytics Server") | |
| # This tells the server what JSON structure to expect from Flutter | |
| class ReportContext(BaseModel): | |
| user_profile: dict | |
| strategy: dict | |
| today_plan: dict | |
| history: list | |
| # Deletes the PDF from the server after it is sent to the user to save space | |
| def cleanup_file(filepath: str): | |
| if os.path.exists(filepath): | |
| os.remove(filepath) | |
| async def generate_report(data: ReportContext, background_tasks: BackgroundTasks): | |
| context_data = data.model_dump() | |
| try: | |
| metrics = calculate_metrics(context_data) | |
| ai_sections = get_ai_analysis(context_data, metrics) | |
| chart_daily = chart_daily_completion(metrics["daily_rates"]) | |
| chart_gauge = chart_goal_proximity_gauge(metrics["goal_proximity"]) | |
| chart_dow = chart_dow_performance(metrics["dow_avg"]) | |
| chart_radar = chart_score_breakdown(metrics) | |
| name = context_data["user_profile"]["name"].replace(" ", "_") | |
| timestamp = datetime.now().strftime("%Y%m%d%H%M%S") | |
| output_path = f"temp_report_{name}_{timestamp}.pdf" | |
| # Build the PDF using your awesome layout | |
| build_pdf( | |
| context_data, metrics, ai_sections, | |
| chart_daily, chart_gauge, chart_dow, chart_radar, | |
| output_path | |
| ) | |
| # Schedule the cleanup, then send the file! | |
| background_tasks.add_task(cleanup_file, output_path) | |
| return FileResponse( | |
| path=output_path, | |
| media_type="application/pdf", | |
| filename=f"FocusDesk_{name}.pdf" | |
| ) | |
| except Exception as e: | |
| return {"error": str(e)} |