Voucher-Generator / gemini_utils.py
Sidd-mukho77
Claude Sonnet 4.5
feat: Add Supabase integration for voucher logging and storage
bf26a87
Raw History Blame Contribute Delete
14.5 kB
"""
Gemini API utilities with:
1. Native PDF Vision for extraction (no pypdf needed)
2. Google Maps Grounding for accurate hotel addresses
3. Google Search Grounding for hotel search
4. Pydantic structured outputs for reliable parsing
"""
import os
import json
import requests
from google import genai
from google.genai import types
from pydantic import BaseModel, Field
from typing import List, Optional
# Pydantic models for structured extraction
class GuestRoom(BaseModel):
"""A single guest room booking."""
guest_name: str = Field(description="Full name of the guest")
confirmation_no: str = Field(description="Booking confirmation number")
adults: int = Field(default=2, description="Number of adults")
children: int = Field(default=0, description="Number of children")
class VoucherData(BaseModel):
"""Complete hotel voucher data extracted from PDF."""
hotel_name: str = Field(description="Hotel name only, no descriptions like 'Luxury Hotels'")
city: str = Field(description="City name")
checkin: str = Field(description="Check-in date as written in document")
checkout: str = Field(description="Check-out date as written in document")
room_type: str = Field(description="Room type or category")
room_size: str = Field(default="", description="Room size if specified")
meal_plan: str = Field(description="One of: Breakfast Only, Room Only, Half Board, Full Board")
address_line1: str = Field(default="", description="Street address of hotel")
address_line2: str = Field(default="", description="City and postal code")
phone: str = Field(default="", description="Hotel phone number")
rooms: List[GuestRoom] = Field(description="List of all guest rooms/bookings")
def get_client():
"""Get Gemini client with API key from environment."""
api_key = os.environ.get("GEMINI_API_KEY")
if not api_key:
raise ValueError("GEMINI_API_KEY environment variable not set")
return genai.Client(api_key=api_key)
def extract_pdf_with_vision(pdf_bytes: bytes) -> dict:
"""
Extract booking data from PDF using Gemini 2.5 Flash.
Uses Pydantic structured outputs for guaranteed type-safe parsing.
Optimized for accuracy with minimal thinking.
Args:
pdf_bytes: Raw PDF file bytes
Returns:
dict with hotel_name, city, checkin, checkout, room_type, etc.
"""
client = get_client()
# Clear, structured prompt for extraction
prompt = """Extract all booking details from this hotel booking PDF:
Required fields:
- hotel_name: Hotel name only (no taglines or descriptions)
- city: City name where hotel is located
- checkin: Check-in date as written
- checkout: Check-out date as written
- room_type: Room category or type
- room_size: Room size if mentioned (e.g., "35 sqm")
- meal_plan: Must be one of: "Breakfast Only", "Room Only", "Half Board", "Full Board"
- rooms: Array of all guest bookings with names and confirmation numbers
- address_line1: Hotel street address
- address_line2: City, state, postal code
- phone: Hotel phone number
Extract all guest information accurately."""
try:
# Use gemini-2.5-flash for better accuracy with PDFs
# Flash-Lite can have issues with complex PDF layouts
response = client.models.generate_content(
model="gemini-2.5-flash", # Better for PDF extraction
contents=[
types.Part.from_bytes(data=pdf_bytes, mime_type='application/pdf'),
prompt
],
config=types.GenerateContentConfig(
response_mime_type="application/json",
response_json_schema=VoucherData.model_json_schema(),
thinking_config=types.ThinkingConfig(
thinking_budget=512 # Balanced thinking for accuracy
)
)
)
print(f"DEBUG: PDF extraction successful")
# Parse with Pydantic for type safety
voucher = VoucherData.model_validate_json(response.text)
return voucher.model_dump()
except Exception as e:
print(f"DEBUG: PDF extraction error: {e}")
import traceback
traceback.print_exc()
return {"error": f"Extraction failed: {str(e)}"}
def search_hotels_grounded(query: str) -> list:
"""
Search for hotels using Gemini 2.5 Flash-Lite with Google Search grounding.
ULTRA FAST with accurate hotel data.
Args:
query: Search query (e.g., "Taj Mumbai")
Returns:
List of hotel names in format "Hotel Name, City"
"""
if not query or len(query) < 2:
return []
client = get_client()
# Detailed prompt for better results - request JSON in text
prompt = f"""Search for hotels matching: "{query}"
Return ONLY a valid JSON array (no markdown, no extra text) with 5-8 hotels:
["Hotel Name, City", "Hotel Name, City", ...]
Examples:
["Taj Mahal Palace, Mumbai", "The Oberoi, Mumbai", "ITC Maratha, Mumbai"]
["The Leela Palace, New Delhi", "Taj Palace, New Delhi", "The Imperial, New Delhi"]
Rules:
- Only actual hotels (not restaurants/bars)
- Include city after each hotel name
- Return 5-8 options minimum"""
try:
# IMPORTANT: Cannot use response_mime_type with tools!
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=prompt,
config=types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearch())],
)
)
print(f"DEBUG: Raw response: {response.text[:300]}")
# Clean response text (remove markdown code blocks)
text = response.text.strip()
text = text.replace("```json", "").replace("```", "").strip()
# Parse JSON
hotels = json.loads(text)
# Handle different response formats
if isinstance(hotels, dict):
hotels = hotels.get("hotels", hotels.get("results", hotels.get("data", [])))
if isinstance(hotels, list) and len(hotels) > 0:
# Filter and clean results
valid_hotels = [h for h in hotels if h and isinstance(h, str) and len(h) > 3]
print(f"DEBUG: Found {len(valid_hotels)} valid hotels")
return valid_hotels[:8]
print(f"DEBUG: No valid hotels found")
return [query]
except json.JSONDecodeError as e:
print(f"DEBUG: JSON parse error: {e}")
print(f"DEBUG: Response text: {response.text}")
return [query]
except Exception as e:
print(f"DEBUG: Search error: {e}")
return [query]
def fetch_hotel_with_maps_grounding(hotel_name: str, city: str = "") -> dict:
"""
Fetch hotel details using Gemini 2.5 Flash-Lite with Google Maps Grounding.
Two-step approach: Maps grounding for accuracy, then structured output.
Args:
hotel_name: Name of the hotel
city: Optional city for context
Returns:
dict with address_line1, address_line2, phone, sources
"""
client = get_client()
location_context = f" in {city}" if city else ""
try:
# Step 1: Get grounded info from Google Maps
maps_prompt = f"What is the full address and phone number for {hotel_name}{location_context}?"
maps_response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=maps_prompt,
config=types.GenerateContentConfig(
tools=[types.Tool(google_maps=types.GoogleMaps())],
)
)
# Extract Maps grounding sources
sources = []
maps_info = maps_response.text # Natural language response with Maps data
if hasattr(maps_response, 'candidates') and maps_response.candidates:
candidate = maps_response.candidates[0]
if hasattr(candidate, 'grounding_metadata') and candidate.grounding_metadata:
metadata = candidate.grounding_metadata
if hasattr(metadata, 'grounding_chunks'):
for chunk in metadata.grounding_chunks:
if hasattr(chunk, 'maps') and chunk.maps:
sources.append({
"title": getattr(chunk.maps, 'title', ''),
"uri": getattr(chunk.maps, 'uri', ''),
"place_id": getattr(chunk.maps, 'place_id', '')
})
# Step 2: Parse the Maps info into structured JSON
# Now we can use response_mime_type since we're not using tools
structure_prompt = f"""Based on this hotel information:
{maps_info}
Extract and return ONLY a JSON object with these exact fields:
{{"address_line1": "street address", "address_line2": "city, state/country postal", "phone": "phone number", "check_in_time": "3:00 PM", "check_out_time": "12:00 PM"}}"""
structure_response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=structure_prompt,
config=types.GenerateContentConfig(
response_mime_type="application/json"
)
)
result = json.loads(structure_response.text)
result["sources"] = sources
result["grounded"] = True
return result
except Exception as e:
print(f"Maps grounding error: {e}, falling back to Search grounding")
# Fallback to Google Search grounding
try:
response = client.models.generate_content(
model="gemini-2.5-flash-lite", # Use same fast model
contents=prompt,
config=types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearch())],
)
)
text = response.text.strip().replace("```json", "").replace("```", "").strip()
result = json.loads(text)
result["sources"] = []
result["grounded"] = False
result["note"] = "Used Google Search grounding (Maps grounding unavailable)"
return result
except Exception as e2:
return {
"address_line1": "",
"address_line2": "",
"phone": "",
"check_in_time": "3:00 PM",
"check_out_time": "12:00 PM",
"sources": [],
"grounded": False,
"error": str(e2)
}
def fetch_room_types_grounded(hotel_name: str, city: str = "") -> list:
"""
Fetch available room types for a hotel using Google Search grounding.
ULTRA FAST (<2 seconds) with accurate room type data.
Args:
hotel_name: Name of the hotel
city: Optional city for context
Returns:
List of room type names (e.g., ["Deluxe", "Premium Suite", "Master Suite"])
"""
if not hotel_name:
return ["Standard", "Deluxe", "Superior", "Suite", "Executive"]
client = get_client()
location_context = f" in {city}" if city else ""
# Concise prompt for fast room type extraction
prompt = f"""Find the available room types/categories at "{hotel_name}"{location_context}.
Return ONLY a JSON array of room type names (no markdown, no extra text):
["Room Type 1", "Room Type 2", ...]
Examples:
["Deluxe Room", "Premium Suite", "Executive Room", "Grand Suite"]
["Standard", "Superior", "Deluxe", "Suite"]
Return 5-10 actual room types offered by this specific hotel."""
try:
# Use Flash-Lite with Search grounding for speed
response = client.models.generate_content(
model="gemini-2.5-flash-lite",
contents=prompt,
config=types.GenerateContentConfig(
tools=[types.Tool(google_search=types.GoogleSearch())],
)
)
print(f"DEBUG: Room types response: {response.text[:200]}")
# Clean and parse JSON
text = response.text.strip().replace("```json", "").replace("```", "").strip()
room_types = json.loads(text)
# Handle different response formats
if isinstance(room_types, dict):
room_types = room_types.get("room_types", room_types.get("types", []))
if isinstance(room_types, list) and len(room_types) > 0:
# Filter and clean
valid_types = [rt for rt in room_types if rt and isinstance(rt, str) and len(rt) > 2]
print(f"DEBUG: Found {len(valid_types)} room types")
return valid_types[:10] # Max 10 types
# Fallback to defaults
return ["Standard", "Deluxe", "Superior", "Suite", "Executive"]
except Exception as e:
print(f"DEBUG: Room types fetch error: {e}")
# Return default room types
return ["Standard", "Deluxe", "Superior", "Suite", "Executive"]
def fetch_hotel_images(hotel_name: str, city: str = "") -> list:
"""
Fetch hotel images using Google Custom Search API.
Args:
hotel_name: Name of the hotel
city: City where the hotel is located
Returns:
List of up to 3 image URLs [exterior, lobby, room]
"""
search_api_key = os.environ.get("SEARCH_API_KEY")
search_cx = os.environ.get("SEARCH_ENGINE_ID")
if not search_api_key or not search_cx:
return [None, None, None]
base_query = f"{hotel_name} {city}".strip()
queries = [
f"{base_query} hotel exterior",
f"{base_query} hotel lobby",
f"{base_query} hotel room"
]
images = []
for query in queries:
try:
response = requests.get(
"https://www.googleapis.com/customsearch/v1",
params={
"q": query,
"cx": search_cx,
"key": search_api_key,
"searchType": "image",
"num": 3,
"imgSize": "large",
"safe": "active"
},
timeout=5
)
items = response.json().get("items", [])
# Find first valid image (skip webp)
image_url = None
for item in items:
link = item.get("link", "")
if ".webp" not in link.lower():
image_url = link
break
images.append(image_url)
except:
images.append(None)
return images