triflix commited on
Commit
8b6d9bd
·
verified ·
1 Parent(s): 2bf5216

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +22 -37
app.py CHANGED
@@ -1,7 +1,8 @@
1
  import os
2
  import datetime
3
  import re
4
- import httpx
 
5
  from fastapi import FastAPI, Request, Form
6
  from fastapi.responses import HTMLResponse
7
  from fastapi.templating import Jinja2Templates
@@ -9,55 +10,44 @@ from fastapi.templating import Jinja2Templates
9
  app = FastAPI()
10
  templates = Jinja2Templates(directory="templates")
11
 
12
- # Retrieve the Gemini API key from an environment variable
13
- GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "AIzaSyDcYyq3w21iwipYn17wCAQo3AYWhUIGDSI")
14
- # Hypothetical Gemini API endpoint
15
- GEMINI_API_URL = "https://api.gemini.example/v1/generate"
16
 
17
- async def call_gemini_api(prompt: str) -> str:
18
- """
19
- Call the Gemini API with a given prompt and return the generated text.
20
- """
21
  headers = {
22
- "Authorization": f"Bearer {GEMINI_API_KEY}",
23
  "Content-Type": "application/json"
24
  }
25
- payload = {
26
- "prompt": prompt,
27
- "max_tokens": 60, # Adjust as needed
28
- "temperature": 0.7
29
  }
30
- async with httpx.AsyncClient() as client:
31
- response = await client.post(GEMINI_API_URL, json=payload, headers=headers)
32
- response.raise_for_status()
33
- data = response.json()
34
- # Assume the API returns the generated text in the "text" field
35
- return data.get("text", "Keep exploring coding and robotics!")
36
 
37
  @app.get("/", response_class=HTMLResponse)
38
- async def read_index(request: Request):
39
  return templates.TemplateResponse("index.html", {"request": request})
40
 
41
  @app.post("/fortune", response_class=HTMLResponse)
42
- async def get_fortune(
43
- request: Request,
44
- birthday: str = Form(...),
45
- standard: str = Form(...)
46
- ):
47
- # Validate birthday format (YYYY-MM-DD)
48
  try:
49
- birth_date = datetime.datetime.strptime(birthday, "%Y-%m-%d").date()
50
  except Exception:
51
  return templates.TemplateResponse(
52
  "index.html",
53
  {"request": request, "error": "Invalid date format! Please use YYYY-MM-DD."}
54
  )
55
 
56
- # Extract numeric grade from the standard string (e.g., "1st" -> "1")
57
  grade_match = re.search(r'\d+', standard)
58
  grade = grade_match.group(0) if grade_match else "1"
59
 
60
- # Build a prompt for Gemini API to generate a fortune message
61
  prompt = (
62
  f"You are an inspirational fortune teller for young coders and robotics enthusiasts. "
63
  f"A student with birthday {birthday} and in grade {standard} is curious about technology. "
@@ -66,16 +56,11 @@ async def get_fortune(
66
  )
67
 
68
  try:
69
- fortune_message = await call_gemini_api(prompt)
70
  except Exception as e:
71
  fortune_message = "Coding and robotics hold a bright future for you! Keep dreaming and exploring."
72
 
73
  return templates.TemplateResponse(
74
  "index.html",
75
- {
76
- "request": request,
77
- "fortune": fortune_message,
78
- "birthday": birthday,
79
- "standard": standard
80
- }
81
  )
 
1
  import os
2
  import datetime
3
  import re
4
+ import json
5
+ import requests
6
  from fastapi import FastAPI, Request, Form
7
  from fastapi.responses import HTMLResponse
8
  from fastapi.templating import Jinja2Templates
 
10
  app = FastAPI()
11
  templates = Jinja2Templates(directory="templates")
12
 
13
+ # Retrieve your Gemini API key from environment variables
14
+ GEMINI_API_KEY = os.getenv("GEMINI_API_KEY", "your_api_key_here")
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}]
24
+ }]
25
  }
26
+ response = requests.post(GEMINI_API_URL, headers=headers, data=json.dumps(data))
27
+ response_data = response.json()
28
+ # Assuming the generated text is in the first candidate's "output" field:
29
+ if "candidates" in response_data and len(response_data["candidates"]) > 0:
30
+ return response_data["candidates"][0].get("output", "Keep coding and exploring robotics!")
31
+ return "Keep coding and exploring robotics!"
32
 
33
  @app.get("/", response_class=HTMLResponse)
34
+ def read_index(request: Request):
35
  return templates.TemplateResponse("index.html", {"request": request})
36
 
37
  @app.post("/fortune", response_class=HTMLResponse)
38
+ def get_fortune(request: Request, birthday: str = Form(...), standard: str = Form(...)):
 
 
 
 
 
39
  try:
40
+ datetime.datetime.strptime(birthday, "%Y-%m-%d").date()
41
  except Exception:
42
  return templates.TemplateResponse(
43
  "index.html",
44
  {"request": request, "error": "Invalid date format! Please use YYYY-MM-DD."}
45
  )
46
 
 
47
  grade_match = re.search(r'\d+', standard)
48
  grade = grade_match.group(0) if grade_match else "1"
49
 
50
+ # Construct a prompt that emphasizes coding and robotics
51
  prompt = (
52
  f"You are an inspirational fortune teller for young coders and robotics enthusiasts. "
53
  f"A student with birthday {birthday} and in grade {standard} is curious about technology. "
 
56
  )
57
 
58
  try:
59
+ fortune_message = call_gemini_api(prompt)
60
  except Exception as e:
61
  fortune_message = "Coding and robotics hold a bright future for you! Keep dreaming and exploring."
62
 
63
  return templates.TemplateResponse(
64
  "index.html",
65
+ {"request": request, "fortune": fortune_message, "birthday": birthday, "standard": standard}
 
 
 
 
 
66
  )