Spaces:
Sleeping
Sleeping
| from fastapi import FastAPI, Request, Form | |
| from fastapi.responses import HTMLResponse, Response | |
| from fastapi.staticfiles import StaticFiles | |
| from fastapi.templating import Jinja2Templates | |
| from typing import Dict, List, Optional | |
| import httpx | |
| import json | |
| from googleapiclient.discovery import build | |
| from google.oauth2 import service_account | |
| import os | |
| from datetime import datetime | |
| app = FastAPI() | |
| templates = Jinja2Templates(directory="templates") | |
| GOOGLE_SHEETS_SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly'] | |
| GOOGLE_CREDENTIALS = os.getenv("GOOGLE_CREDENTIALS", "{}") | |
| SHEET_ID = os.getenv("SHEET_ID", "") | |
| SHEET_RANGE = os.getenv("SHEET_RANGE", "Sheet1!A:Z") | |
| def get_sheets_data(): | |
| """Fetch data from Google Sheets""" | |
| try: | |
| if not GOOGLE_CREDENTIALS or GOOGLE_CREDENTIALS == "{}": | |
| return [] | |
| creds_dict = json.loads(GOOGLE_CREDENTIALS) | |
| creds = service_account.Credentials.from_service_account_info( | |
| creds_dict, scopes=GOOGLE_SHEETS_SCOPES | |
| ) | |
| service = build('sheets', 'v4', credentials=creds) | |
| sheet = service.spreadsheets() | |
| result = sheet.values().get( | |
| spreadsheetId=SHEET_ID, | |
| range=SHEET_RANGE | |
| ).execute() | |
| values = result.get('values', []) | |
| if not values: | |
| return [] | |
| headers = values[0] | |
| data = [] | |
| for row in values[1:]: | |
| record = {} | |
| for i, header in enumerate(headers): | |
| record[header] = row[i] if i < len(row) else "" | |
| data.append(record) | |
| return data | |
| except Exception as e: | |
| print(f"Error fetching Google Sheets data: {e}") | |
| return [] | |
| async def index(request: Request): | |
| awards_data = get_sheets_data() | |
| return templates.TemplateResponse( | |
| "index.html", | |
| { | |
| "request": request, | |
| "awards_data": awards_data | |
| } | |
| ) | |
| async def generate_html( | |
| template_content: str = Form(...), | |
| variables: str = Form("{}") | |
| ): | |
| try: | |
| variables_dict = json.loads(variables) | |
| awards_data = get_sheets_data() | |
| variables_dict['awards_data'] = awards_data | |
| variables_dict['current_year'] = datetime.now().year | |
| from jinja2 import Template | |
| template = Template(template_content) | |
| generated_html = template.render(**variables_dict) | |
| return Response( | |
| content=generated_html, | |
| media_type="text/html", | |
| headers={ | |
| "Content-Disposition": f"attachment; filename=generated_{datetime.now().strftime('%Y%m%d_%H%M%S')}.html" | |
| } | |
| ) | |
| except Exception as e: | |
| return {"error": str(e)} | |
| async def get_awards(): | |
| """API endpoint to fetch awards data""" | |
| return {"awards": get_sheets_data()} | |
| async def preview_html( | |
| template_content: str = Form(...), | |
| variables: str = Form("{}") | |
| ): | |
| """API endpoint to preview HTML with variables""" | |
| try: | |
| variables_dict = json.loads(variables) | |
| awards_data = get_sheets_data() | |
| variables_dict['awards_data'] = awards_data | |
| variables_dict['current_year'] = datetime.now().year | |
| from jinja2 import Template | |
| template = Template(template_content) | |
| generated_html = template.render(**variables_dict) | |
| return { | |
| "html": generated_html, | |
| "debug": { | |
| "variables_count": len(variables_dict), | |
| "html_length": len(generated_html), | |
| "template_length": len(template_content) | |
| } | |
| } | |
| except Exception as e: | |
| import traceback | |
| return { | |
| "error": str(e), | |
| "html": "", | |
| "debug": { | |
| "error_type": type(e).__name__, | |
| "traceback": traceback.format_exc() | |
| } | |
| } |