""" Odaduu Voucher Generator - Gradio Version Features: 1. PDF Upload with Gemini Vision extraction 2. Hotel Search with Google Search grounding 3. Address fetch with Google Maps grounding 4. All forms visible - no hidden workflow """ import gradio as gr import pandas as pd from datetime import datetime, timedelta, date import os import re # Load environment variables FIRST from dotenv import load_dotenv load_dotenv() # Debug: Print environment variables status print("DEBUG: Starting App...") print(f"DEBUG: GEMINI_API_KEY set: {bool(os.environ.get('GEMINI_API_KEY'))}") print(f"DEBUG: SEARCH_API_KEY set: {bool(os.environ.get('SEARCH_API_KEY'))}") print(f"DEBUG: SEARCH_ENGINE_ID set: {bool(os.environ.get('SEARCH_ENGINE_ID'))}") print(f"DEBUG: SUPABASE_URL set: {bool(os.environ.get('SUPABASE_URL'))}") print(f"DEBUG: SUPABASE_KEY set: {bool(os.environ.get('SUPABASE_KEY'))}") # Define output directory for generated PDFs (Absolute Path) OUTPUT_DIR = os.path.abspath("output") os.makedirs(OUTPUT_DIR, exist_ok=True) from gemini_utils import ( extract_pdf_with_vision, search_hotels_grounded, fetch_hotel_with_maps_grounding, fetch_hotel_images, fetch_room_types_grounded ) from voucher_generator import generate_voucher_pdf from supabase_logger import log_and_upload_voucher def make_date_range_html(tab_id): """ HTML-only wrapper for the Flatpickr date range picker. Scripts are NOT included here because Svelte's {@ html} does not execute """ filename = f"ag_grid_{_uuid.uuid4().hex[:10]}.html" filepath = os.path.join(OUTPUT_DIR, filename) with open(filepath, 'w', encoding='utf-8') as _f: _f.write(html) # Keep only newest 10 grid files try: old_files = sorted( [os.path.join(OUTPUT_DIR, x) for x in os.listdir(OUTPUT_DIR) if x.startswith('ag_grid_') and x.endswith('.html')], key=os.path.getmtime ) for old in old_files[:-10]: os.remove(old) except Exception: pass url_path = filepath.replace('\\', '/') return f'' def preview_csv_upload(csv_file): """ Preview uploaded CSV file in an AG Grid table. Shows first 100 rows and validates required columns for guest list. Returns (ag_grid_html, info_markdown, json_data). """ if not csv_file: return ( gr.update(value="", visible=False), # Hide AG Grid gr.update(visible=False), # Hide info "" # Empty JSON ) try: # Read first 100 rows for preview df_preview = pd.read_csv(csv_file, nrows=100) # Strip whitespace from column names df_preview.columns = df_preview.columns.str.strip() # Get total row count total_rows = sum(1 for _ in open(csv_file, encoding='utf-8')) - 1 # Subtract header # Create column mapping for flexible matching column_mapping = {} for col in df_preview.columns: col_upper = col.upper() if 'GUEST' in col_upper and 'NAME' in col_upper: column_mapping[col] = 'Guest Name' elif 'CONFIRMATION' in col_upper: column_mapping[col] = 'Confirmation No' elif col_upper == 'ADULTS': column_mapping[col] = 'Adults' elif 'CHILD' in col_upper: column_mapping[col] = 'Children' # Check which standard columns we found found_guest = 'Guest Name' in column_mapping.values() found_adults = 'Adults' in column_mapping.values() found_children = 'Children' in column_mapping.values() found_conf = 'Confirmation No' in column_mapping.values() # Build info message info_msg = f"**šŸ“Š Guest List Loaded:** {total_rows} guests, {len(df_preview.columns)} columns" if total_rows > 100: info_msg += f"\n\n*Showing first 100 of {total_rows} guests*" # Check for missing required columns missing_cols = [] if not found_guest: missing_cols.append('Guest Name/GUESTS NAME') if not found_adults: missing_cols.append('Adults/ADULTS') if not found_children: missing_cols.append('Children/CHILD') if missing_cols: info_msg += f"\n\nāš ļø **Missing required columns:** `{', '.join(missing_cols)}`" info_msg += f"\n\n**Found columns:** `{', '.join(df_preview.columns)}`" else: info_msg += f"\n\nāœ… **All required columns present**" if not found_conf: info_msg += f"\n\nšŸ’” **Optional:** Confirmation No column missing (will use blank)" # Count guests - use original column names for counting adults_col = [k for k, v in column_mapping.items() if v == 'Adults'] children_col = [k for k, v in column_mapping.items() if v == 'Children'] total_adults = df_preview[adults_col[0]].sum() if adults_col else 0 total_children = df_preview[children_col[0]].sum() if children_col else 0 info_msg += f"\n\n**šŸ“ˆ Total:** {total_adults} adults, {total_children} children across {total_rows} voucher pages" # Rename columns to standard names so edits use consistent column headers df_preview.rename(columns=column_mapping, inplace=True) # Ensure Confirmation No column exists (fill blank if missing) if 'Confirmation No' not in df_preview.columns: df_preview['Confirmation No'] = '' # Fill NaN confirmation numbers with empty string for display df_preview['Confirmation No'] = df_preview['Confirmation No'].fillna('').astype(str) # Clean 'nan' strings df_preview['Confirmation No'] = df_preview['Confirmation No'].replace('nan', '') import json as _json grid_html = build_ag_grid_html(df_preview) grid_json = _json.dumps(df_preview.to_dict(orient='records')) return ( gr.update(value=grid_html, visible=True), gr.update(value=info_msg, visible=True), grid_json ) except Exception as e: error_msg = f"āŒ **Error reading CSV:** {str(e)}\n\nPlease check file format and encoding." return ( gr.update(value="", visible=False), gr.update(value=error_msg, visible=True), "" ) # --------------------------------------------------------------------------- # Flatpickr initialization JS — injected via demo.launch(js=...) so it runs # in the main page context (Svelte's {@html} does NOT execute