triflix commited on
Commit
3c1035e
·
verified ·
1 Parent(s): 8599ad0

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -25
app.py CHANGED
@@ -1,6 +1,4 @@
1
  import os
2
- import datetime
3
- import re
4
  import json
5
  import requests
6
  from fastapi import FastAPI, Request, Form
@@ -10,14 +8,12 @@ from fastapi.templating import Jinja2Templates
10
  app = FastAPI()
11
  templates = Jinja2Templates(directory="templates")
12
 
13
- # Get your Gemini API key from environment variables
14
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "AIzaSyDcYyq3w21iwipYn17wCAQo3AYWhUIGDSI")
15
  GEMINI_API_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={GEMINI_API_KEY}"
16
 
17
  def call_gemini_api(prompt: str) -> str:
18
- headers = {
19
- "Content-Type": "application/json"
20
- }
21
  data = {
22
  "contents": [{
23
  "parts": [{"text": prompt}]
@@ -27,42 +23,43 @@ def call_gemini_api(prompt: str) -> str:
27
  response = requests.post(GEMINI_API_URL, headers=headers, data=json.dumps(data))
28
  response.raise_for_status()
29
  response_data = response.json()
30
- # Expecting the API to return candidates with an "output" field.
31
- if "candidates" in response_data and len(response_data["candidates"]) > 0:
32
- return response_data["candidates"][0].get("output", "Keep coding and stay inspired!")
33
- return "Keep coding and stay inspired!"
 
34
  except Exception as e:
 
35
  return "Keep coding and stay inspired!"
36
 
37
  @app.get("/", response_class=HTMLResponse)
38
  def index(request: Request):
 
39
  return templates.TemplateResponse("index.html", {"request": request})
40
 
41
  @app.post("/fortune", response_class=HTMLResponse)
42
- def fortune(request: Request, birthday: str = Form(...), standard: str = Form(...)):
43
- try:
44
- datetime.datetime.strptime(birthday, "%Y-%m-%d").date()
45
- except Exception:
46
- return templates.TemplateResponse(
47
- "index.html",
48
- {"request": request, "error": "Invalid birthday format! Please use YYYY-MM-DD."}
49
- )
50
-
51
- # Build a prompt that uses the provided birthday and standard.
52
  prompt = (
53
  f"You are an inspirational fortune teller for young coders. "
54
- f"Here's the birthday: {birthday}. For a student in standard {standard}, "
55
- f"provide a random, modern, concise, and energetic quote that inspires them to code and explore robotics."
56
  )
57
-
58
  fortune_message = call_gemini_api(prompt)
59
 
 
60
  return templates.TemplateResponse(
61
  "index.html",
62
  {
63
  "request": request,
64
  "fortune": fortune_message,
65
- "birthday": birthday,
 
66
  "standard": standard
67
  }
68
  )
 
1
  import os
 
 
2
  import json
3
  import requests
4
  from fastapi import FastAPI, Request, Form
 
8
  app = FastAPI()
9
  templates = Jinja2Templates(directory="templates")
10
 
11
+ # Get your Gemini API key from environment variables (or replace with your key)
12
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "your_api_key_here")
13
  GEMINI_API_URL = f"https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash:generateContent?key={GEMINI_API_KEY}"
14
 
15
  def call_gemini_api(prompt: str) -> str:
16
+ headers = {"Content-Type": "application/json"}
 
 
17
  data = {
18
  "contents": [{
19
  "parts": [{"text": prompt}]
 
23
  response = requests.post(GEMINI_API_URL, headers=headers, data=json.dumps(data))
24
  response.raise_for_status()
25
  response_data = response.json()
26
+ # Parse the response based on the sample output structure:
27
+ candidate = response_data.get("candidates", [{}])[0]
28
+ # The text is nested under candidate["content"]["parts"][0]["text"]
29
+ fortune_text = candidate.get("content", {}).get("parts", [{}])[0].get("text", "")
30
+ return fortune_text.strip() if fortune_text else "Keep coding and stay inspired!"
31
  except Exception as e:
32
+ print("Error calling Gemini API:", e)
33
  return "Keep coding and stay inspired!"
34
 
35
  @app.get("/", response_class=HTMLResponse)
36
  def index(request: Request):
37
+ # Initially show the form.
38
  return templates.TemplateResponse("index.html", {"request": request})
39
 
40
  @app.post("/fortune", response_class=HTMLResponse)
41
+ def fortune(
42
+ request: Request,
43
+ name: str = Form(...),
44
+ roll_number: str = Form(...),
45
+ standard: str = Form(...)
46
+ ):
47
+ # Build a prompt using the provided user info.
 
 
 
48
  prompt = (
49
  f"You are an inspirational fortune teller for young coders. "
50
+ f"A student with Name: {name}, Roll Number: {roll_number}, and Standard: {standard} seeks a fortune. "
51
+ f"Provide a random, modern, concise, and energetic quote that inspires them to code and explore robotics."
52
  )
 
53
  fortune_message = call_gemini_api(prompt)
54
 
55
+ # Pass the generated fortune (and user info, if needed) to the template.
56
  return templates.TemplateResponse(
57
  "index.html",
58
  {
59
  "request": request,
60
  "fortune": fortune_message,
61
+ "name": name,
62
+ "roll_number": roll_number,
63
  "standard": standard
64
  }
65
  )