|
|
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") |
|
|
|
|
|
|
|
|
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() |
|
|
|
|
|
candidate = response_data.get("candidates", [{}])[0] |
|
|
|
|
|
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): |
|
|
|
|
|
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(...) |
|
|
): |
|
|
|
|
|
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) |
|
|
|
|
|
|
|
|
return templates.TemplateResponse( |
|
|
"index.html", |
|
|
{ |
|
|
"request": request, |
|
|
"fortune": fortune_message, |
|
|
"name": name, |
|
|
"roll_number": roll_number, |
|
|
"standard": standard |
|
|
} |
|
|
) |
|
|
|