goodwill / app.py
triflix's picture
Update app.py
3c1035e verified
import os
import json
import requests
from fastapi import FastAPI, Request, Form
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
app = FastAPI()
templates = Jinja2Templates(directory="templates")
# Get your Gemini API key from environment variables (or replace with your key)
GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "your_api_key_here")
GEMINI_API_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={GEMINI_API_KEY}"
def call_gemini_api(prompt: str) -> str:
headers = {"Content-Type": "application/json"}
data = {
"contents": [{
"parts": [{"text": prompt}]
}]
}
try:
response = requests.post(GEMINI_API_URL, headers=headers, data=json.dumps(data))
response.raise_for_status()
response_data = response.json()
# Parse the response based on the sample output structure:
candidate = response_data.get("candidates", [{}])[0]
# The text is nested under candidate["content"]["parts"][0]["text"]
fortune_text = candidate.get("content", {}).get("parts", [{}])[0].get("text", "")
return fortune_text.strip() if fortune_text else "Keep coding and stay inspired!"
except Exception as e:
print("Error calling Gemini API:", e)
return "Keep coding and stay inspired!"
@app.get("/", response_class=HTMLResponse)
def index(request: Request):
# Initially show the form.
return templates.TemplateResponse("index.html", {"request": request})
@app.post("/fortune", response_class=HTMLResponse)
def fortune(
request: Request,
name: str = Form(...),
roll_number: str = Form(...),
standard: str = Form(...)
):
# Build a prompt using the provided user info.
prompt = (
f"You are an inspirational fortune teller for young coders. "
f"A student with Name: {name}, Roll Number: {roll_number}, and Standard: {standard} seeks a fortune. "
f"Provide a random, modern, concise, and energetic quote that inspires them to code and explore robotics."
)
fortune_message = call_gemini_api(prompt)
# Pass the generated fortune (and user info, if needed) to the template.
return templates.TemplateResponse(
"index.html",
{
"request": request,
"fortune": fortune_message,
"name": name,
"roll_number": roll_number,
"standard": standard
}
)