Sidd-mukho77
Claude Sonnet 4.6
fix: Use gr.Dataframe.select() to track row for Delete Row button
99cdd1e
Raw History Blame Contribute Delete
90.1 kB
""" 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 <script> tags. The JS initialization is handled via demo.launch(js=FLATPICKR_JS). """ return f"""<div style="margin-bottom:4px;"> <style> .dr-wrap-{tab_id} {{ position: relative; }} .dr-wrap-{tab_id} input {{ width: 100%; padding: 8px 40px 8px 12px; background: var(--input-background-fill, #1f2937); border: 1px solid var(--input-border-color, #374151); border-radius: 8px; color: var(--body-text-color, #f3f4f6); font-size: 14px; cursor: pointer; box-sizing: border-box; font-family: inherit; transition: border-color 0.15s; }} .dr-wrap-{tab_id} input:hover {{ border-color: #6366f1; outline: none; }} .dr-wrap-{tab_id} input::placeholder {{ color: #9ca3af; }} .dr-icon-{tab_id} {{ position: absolute; right: 10px; top: 50%; transform: translateY(-50%); pointer-events: none; color: #9ca3af; }} </style> <div class="dr-wrap-{tab_id}"> <input id="dr-{tab_id}" type="text" placeholder="Click to select check-in β†’ check-out" readonly> <span class="dr-icon-{tab_id}"> <svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"> <rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect> <line x1="16" y1="2" x2="16" y2="6"></line> <line x1="8" y1="2" x2="8" y2="6"></line> <line x1="3" y1="10" x2="21" y2="10"></line> </svg> </span> </div> </div>""" def create_pdf_viewer(pdf_path): """Create PDF preview by converting first page to image""" if not pdf_path or not os.path.exists(pdf_path): return '<div style="height:600px;background:#2a2a3e;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#888;font-size:18px;">πŸ“„ Preview will appear here after generation</div>' try: import fitz # PyMuPDF import base64 from io import BytesIO from PIL import Image # Get file info file_size_kb = os.path.getsize(pdf_path) / 1024 file_name = os.path.basename(pdf_path) # Open PDF and convert first page to image doc = fitz.open(pdf_path) # For multi-page PDFs, show first page info total_pages = len(doc) page = doc[0] # First page # Render page at high resolution (2x for quality) mat = fitz.Matrix(2, 2) pix = page.get_pixmap(matrix=mat) # Convert to PIL Image img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples) # Save to base64 buffered = BytesIO() img.save(buffered, format="PNG", optimize=True) img_base64 = base64.b64encode(buffered.getvalue()).decode('utf-8') doc.close() # Create HTML with image preview page_info = f"{total_pages} pages" if total_pages > 1 else "1 page" html = f''' <div style="width:100%;background:#2a2a3e;border-radius:8px;overflow:hidden;box-shadow:0 4px 12px rgba(0,0,0,0.3);"> <div style="background:#1e1e2e;padding:12px 16px;color:#fff;font-size:14px;border-bottom:2px solid #444;display:flex;justify-content:space-between;align-items:center;"> <span>πŸ“„ <strong>{file_name}</strong> ({file_size_kb:.1f} KB, {page_info})</span> <span style="font-size:12px;color:#888;">Preview Page 1 β€’ Download for full quality</span> </div> <div style="max-height:600px;overflow-y:auto;background:#fff;padding:20px;display:flex;justify-content:center;"> <img src="data:image/png;base64,{img_base64}" alt="PDF Preview - Page 1" style="max-width:100%;height:auto;box-shadow:0 2px 8px rgba(0,0,0,0.2);border-radius:4px;" /> </div> </div> ''' return html except ImportError as e: return f'''<div style="height:600px;background:#2a2a3e;border-radius:8px;display:flex;align-items:center;justify-content:center;flex-direction:column;color:#888;font-size:16px;padding:40px;text-align:center;"> <div style="font-size:48px;margin-bottom:20px;">πŸ“„</div> <div style="font-size:18px;color:#fff;margin-bottom:10px;">Preview Unavailable</div> <div style="font-size:14px;margin-bottom:20px;">PyMuPDF not installed. Please run:<br/><code style="background:#1e1e2e;padding:8px 12px;border-radius:4px;margin-top:10px;display:inline-block;">pip install PyMuPDF</code></div> <div style="font-size:14px;color:#aaa;">Click the download button above to view the PDF</div> </div>''' except Exception as e: import traceback traceback.print_exc() return f'<div style="height:600px;background:#3d1e1e;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#ff6b6b;font-size:16px;padding:20px;text-align:center;">⚠️ Error creating preview<br/><small>{str(e)}</small></div>' def parse_date(date_input): """Parse various date formats to datetime.date Handles formats like: - "Wednesday, 27th Aug 2025" - "Friday 29th Aug 2025" - "27 Aug 2025" - "2025-08-27" - "27/08/2025" - datetime.date objects (returned as-is) - datetime.datetime objects (extract date) """ if date_input is None: return None # If already a date object, return it from datetime import date if isinstance(date_input, date): return date_input # If datetime object, extract date if isinstance(date_input, datetime): return date_input.date() # Otherwise, parse as string clean_str = str(date_input).strip() # Remove day names (Monday, Tuesday, etc.) at the beginning day_pattern = r'^(Monday|Tuesday|Wednesday|Thursday|Friday|Saturday|Sunday)[,\s]*' clean_str = re.sub(day_pattern, '', clean_str, flags=re.IGNORECASE).strip() # Remove ordinal suffixes (1st, 2nd, 3rd, 4th, 11th, 12th, 13th, 21st, 22nd, 23rd, 31st) clean_str = re.sub(r'(\d+)(st|nd|rd|th)\b', r'\1', clean_str, flags=re.IGNORECASE) # Handle YYYY/MM/DD format if '/' in clean_str and len(clean_str.split('/')[0]) == 4: try: return datetime.strptime(clean_str, "%Y/%m/%d").date() except: pass # Normalize "Sept" to "Sep" clean_str = re.sub(r'\bSept\b', 'Sep', clean_str, flags=re.IGNORECASE) # Try various date formats formats = [ "%Y-%m-%d %H:%M:%S", # 2025-08-27 00:00:00 (DateTimeRange string output) "%d %b %Y", # 27 Aug 2025 "%d %B %Y", # 27 August 2025 "%Y-%m-%d", # 2025-08-27 "%d/%m/%Y", # 27/08/2025 "%m/%d/%Y", # 08/27/2025 "%Y/%m/%d", # 2025/08/27 "%b %d, %Y", # Aug 27, 2025 "%B %d, %Y", # August 27, 2025 "%d-%b-%Y", # 27-Aug-2025 "%d-%B-%Y", # 27-August-2025 ] for fmt in formats: try: return datetime.strptime(clean_str, fmt).date() except ValueError: continue # Last resort: try to extract date components using regex # Pattern: any number (day), optional month name/number, year match = re.search(r'(\d{1,2})\s*([A-Za-z]+)\s*(\d{4})', clean_str) if match: day, month_str, year = match.groups() month_map = { 'jan': 1, 'feb': 2, 'mar': 3, 'apr': 4, 'may': 5, 'jun': 6, 'jul': 7, 'aug': 8, 'sep': 9, 'oct': 10, 'nov': 11, 'dec': 12, 'january': 1, 'february': 2, 'march': 3, 'april': 4, 'june': 6, 'july': 7, 'august': 8, 'september': 9, 'october': 10, 'november': 11, 'december': 12 } month = month_map.get(month_str.lower()) if month: try: from datetime import date return date(int(year), month, int(day)) except: pass return None def generate_default_filename(hotel_name="", confirmation_no="", is_bulk=False): """ Generate default PDF filename based on hotel name and confirmation number. Args: hotel_name: Hotel name confirmation_no: Confirmation number (for single voucher) or empty for bulk is_bulk: True if generating bulk/multi-page PDF Returns: Default filename string """ import re from datetime import datetime # Sanitize hotel name safe_hotel = re.sub(r'[^\w\s-]', '', hotel_name).strip() safe_hotel = re.sub(r'[-\s]+', '_', safe_hotel) or "Hotel" if is_bulk: # For bulk: HotelName_AllVouchers_YYYYMMDD_HHMMSS.pdf timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") return f"{safe_hotel}_AllVouchers_{timestamp}.pdf" else: # For single: HotelName-ConfirmationNo.pdf safe_conf = re.sub(r'[^\w-]', '', confirmation_no).strip() if safe_conf: return f"{safe_hotel}-{safe_conf}.pdf" else: return f"{safe_hotel}_Voucher.pdf" def calculate_nights(checkin_str, checkout_str): """Calculate number of nights between check-in and check-out dates. Returns (nights, warning_message)""" checkin = parse_date(checkin_str) checkout = parse_date(checkout_str) if checkin and checkout: nights = (checkout - checkin).days # Validation: Check-out must be after check-in if nights < 1: return 1, "## ❌ Invalid Dates\n**Check-out date must be after check-in date**" return nights, "" return 1, "" def extract_from_pdf(pdf_file): """Extract booking data from uploaded PDF using Gemini Vision with structured output""" if pdf_file is None: return [gr.update()] * 14 + ["Please upload a PDF file first."] # In gradio_pdf, pdf_file is just the path as a string (if processed) or we need to handle it. # Standard gradio file output is a path. try: with open(pdf_file, 'rb') as f: pdf_bytes = f.read() except Exception as e: return [gr.update()] * 14 + [f"Error reading PDF: {str(e)}"] result = extract_pdf_with_vision(pdf_bytes) if "error" in result: return [gr.update()] * 14 + [f"Extraction error: {result['error']}"] # Convert rooms to Dataframe format rooms = result.get("rooms", []) guest_table_data = [] for room in rooms: guest_table_data.append([ room.get("guest_name", ""), room.get("confirmation_no", ""), room.get("adults", 2), room.get("children", 0) ]) if not guest_table_data: guest_table_data = [["", "", 2, 0]] # Normalize meal plan meal_plan_raw = result.get("meal_plan", "").lower() meal_plan_map = { "breakfast": "Breakfast Only", "breakfast only": "Breakfast Only", "room only": "Room Only", "half board": "Half Board", "full board": "Full Board", "bed and breakfast": "Breakfast Only", } meal_plan = meal_plan_map.get(meal_plan_raw, result.get("meal_plan", "Breakfast Only")) # Get hotel name for populating search field hotel_name_val = result.get("hotel_name", "") # Calculate nights from extracted dates (now returns tuple) nights, night_warning = calculate_nights(result.get("checkin", ""), result.get("checkout", "")) # Build status message status_msg = f"Extracted {len(rooms)} guest(s), {nights} night(s). Review and edit as needed." if night_warning: status_msg = f"{night_warning}\n{status_msg}" checkin_str = result.get("checkin", "") or "" checkout_str = result.get("checkout", "") or "" return [ hotel_name_val, # hotel_name_pdf result.get("city", ""), # city_pdf checkin_str, # checkin_date_pdf checkout_str, # checkout_date_pdf nights, # number_of_nights_pdf result.get("room_type", "Standard"), # room_type_select_pdf result.get("room_size", ""), # room_size_pdf meal_plan, # meal_plan_pdf gr.update(), # remarks_pdf - do NOT autofill result.get("address_line1", ""), # address_line1_pdf result.get("address_line2", ""), # address_line2_pdf result.get("phone", ""), # phone_pdf guest_table_data, # guest_table_pdf status_msg # status_text_pdf ] def search_hotels(query): """Search for hotels and return dropdown choices""" if not query or len(query) < 2: return gr.update(choices=[], value=None) hotels = search_hotels_grounded(query) if hotels: return gr.update(choices=hotels, value=hotels[0]) return gr.update(choices=[query], value=query) def on_hotel_selected(selected_hotel): """When hotel is selected, fetch address and room types using Search/Maps grounding""" if not selected_hotel: return "", "", "", "", "", gr.update() # Parse hotel name from format "Hotel Name, City/Pincode" parts = selected_hotel.split(",") hotel_name = parts[0].strip() if parts else selected_hotel extracted_city = parts[1].strip() if len(parts) > 1 else "" # Fetch hotel info with Maps grounding info = fetch_hotel_with_maps_grounding(hotel_name, extracted_city) addr1 = info.get("address_line1", "") addr2 = info.get("address_line2", "") phone = info.get("phone", "") # Extract city from address if not already found if not extracted_city and addr2: # Try to get city from address_line2 extracted_city = addr2.split(",")[0].strip() if "," in addr2 else addr2 # Fetch actual room types for this hotel room_types = fetch_room_types_grounded(hotel_name, extracted_city) # Update room type dropdown with fetched types room_type_update = gr.update(choices=room_types, value=room_types[0] if room_types else "Standard") return hotel_name, extracted_city, addr1, addr2, phone, room_type_update # Wrapper functions for different tabs def generate_voucher_search_tab( hotel_name, city, checkin_date, checkout_date, number_of_nights, room_type_select, room_size, meal_plan, remarks, policy, cancellation_days, guest_table, address_line1, address_line2, phone, pdf_filename="" ): """Wrapper for Search Hotel tab.""" return generate_voucher( hotel_name, city, checkin_date, checkout_date, number_of_nights, room_type_select, room_size, meal_plan, remarks, policy, cancellation_days, guest_table, address_line1, address_line2, phone, pdf_filename, tab_source="Search Hotel" ) def generate_voucher_pdf_tab( hotel_name, city, checkin_date, checkout_date, number_of_nights, room_type_select, room_size, meal_plan, remarks, policy, cancellation_days, guest_table, address_line1, address_line2, phone, pdf_filename="" ): """Wrapper for PDF Extraction tab.""" return generate_voucher( hotel_name, city, checkin_date, checkout_date, number_of_nights, room_type_select, room_size, meal_plan, remarks, policy, cancellation_days, guest_table, address_line1, address_line2, phone, pdf_filename, tab_source="PDF Extraction" ) def generate_voucher( hotel_name, city, checkin_date, checkout_date, number_of_nights, room_type_select, room_size, meal_plan, remarks, policy, cancellation_days, guest_table, address_line1, address_line2, phone, pdf_filename="", tab_source="Search Hotel" ): """Generate the voucher PDF with all guests on a single page""" # Parse dates checkin = parse_date(checkin_date) if isinstance(checkin_date, str) else checkin_date checkout = parse_date(checkout_date) if isinstance(checkout_date, str) else checkout_date if not checkin: checkin = datetime.now().date() if not checkout: checkout = checkin + timedelta(days=1) # VALIDATION: Check-out must be after check-in if checkout <= checkin: error_preview = create_pdf_viewer(None) return None, error_preview, "❌ Error: Check-out date must be after check-in date" # VALIDATION: Cancellation date must be before check-in (for Free Cancellation policy) if policy == "Free Cancellation" and cancellation_days: try: days = int(cancellation_days) cancellation_deadline = checkin - timedelta(days=days) if cancellation_deadline >= checkin: error_preview = create_pdf_viewer(None) return None, error_preview, "❌ Error: Cancellation deadline must be before check-in date" except: pass # Use the provided number_of_nights if valid, otherwise calculate if number_of_nights and int(number_of_nights) >= 1: nights = int(number_of_nights) else: nights = (checkout - checkin).days if nights < 1: nights = 1 room_name = room_type_select def _si(val, default): """Safe int that handles "2", "2.0", 2, 2.0 from any source.""" try: return max(0, int(float(str(val).strip()))) except Exception: return default # Build rooms list from Dataframe β€” each non-empty row = one PDF page rooms = [] rows_list = (guest_table.values.tolist() if hasattr(guest_table, 'values') else (guest_table or [])) for row in rows_list: if len(row) < 1: continue guest_name = str(row[0]).strip() if row[0] else "" if not guest_name: # skip completely blank rows continue rooms.append({ "guest": guest_name, "conf": str(row[1]).strip() if len(row) > 1 and row[1] else "", "adults": _si(row[2] if len(row) > 2 else 2, 2), "children": _si(row[3] if len(row) > 3 else 0, 0), }) # Ensure at least one room so generation never fails if not rooms: rooms = [{"guest": "", "conf": "", "adults": 2, "children": 0}] # `rooms` is passed directly β€” generate_voucher_pdf creates one page per entry combined_rooms = rooms booking_data = { "hotel": hotel_name, "checkin": checkin, "checkout": checkout, "room_type": room_name, "room_size": room_size or "", "meal_plan": meal_plan, "remarks": remarks or "", "cancellation": policy, "cancellation_days": int(cancellation_days) if policy == "Free Cancellation" and cancellation_days else None, "nights": nights } hotel_info = { "address_line1": address_line1 or "", "address_line2": address_line2 or "", "phone": phone or "" } # Fetch images images = fetch_hotel_images(hotel_name, city) # Get logo path logo_path = "logo.png" if not os.path.exists(logo_path): logo_path = None try: pdf_bytes = generate_voucher_pdf( booking_data=booking_data, hotel_info=hotel_info, rooms=combined_rooms, # One entry per table row β†’ one PDF page each image_urls=images, logo_path=logo_path ) # Save to local directory 'output' instead of system temp to ensure access # output_dir = "output" # REMOVED: Defined globally as OUTPUT_DIR # os.makedirs(output_dir, exist_ok=True) # REMOVED: Created globally # Use custom filename if provided, otherwise generate default if pdf_filename and pdf_filename.strip(): filename = pdf_filename.strip() if not filename.endswith('.pdf'): filename += '.pdf' else: safe_name = re.sub(r'[^\w\-]', '_', hotel_name or "Voucher") filename = f"Voucher_{safe_name}.pdf" output_path = os.path.join(OUTPUT_DIR, filename) with open(output_path, 'wb') as f: f.write(pdf_bytes) print(f"DEBUG: PDF saved to: {output_path}") # Log to Supabase (upload PDF + insert database record) supabase_result = log_and_upload_voucher( booking_data=booking_data, hotel_info=hotel_info, rooms=combined_rooms, pdf_bytes=pdf_bytes, pdf_filename=filename, tab_source=tab_source, city=city, is_bulk=False ) # Return download file, preview HTML, and status message preview_html = create_pdf_viewer(output_path) status_msg = f"βœ“ Generated single-page voucher for {len(rooms)} guest(s), {nights} night(s)" # Add Supabase status to message if supabase_result["success"]: status_msg += f"\n{supabase_result['message']}" else: status_msg += f"\n⚠️ Supabase logging failed: {supabase_result['error']}" return output_path, preview_html, status_msg except Exception as e: import traceback traceback.print_exc() error_preview = create_pdf_viewer(None) return None, error_preview, f"Error: {str(e)}" def process_bulk_csv( csv_file, csv_grid_json, hotel_name, city, checkin_date, checkout_date, number_of_nights, room_type_select, room_size, meal_plan, remarks, policy, cancellation_days, address_line1, address_line2, phone, pdf_filename="", progress=gr.Progress() ): """Process CSV file with guest data and generate single multi-page PDF voucher""" error_preview = create_pdf_viewer(None) if not csv_file: return None, error_preview, "Please upload a CSV file with guest information" if not hotel_name: return None, error_preview, "Please select a hotel first" import pandas as pd import json as _json try: # Use the AG Grid JSON data if available; otherwise fall back to raw CSV df = None if csv_grid_json and csv_grid_json.strip(): try: rows = _json.loads(csv_grid_json) if rows and len(rows) > 0: df = pd.DataFrame(rows) except _json.JSONDecodeError: df = None if df is None: # Fallback: read directly from the uploaded CSV file if not csv_file: return None, error_preview, "Please upload a CSV file with guest information" df = pd.read_csv(csv_file) df.columns = df.columns.str.strip() # Normalize column names column_mapping = {} for col in df.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' df.rename(columns=column_mapping, inplace=True) # Check for required columns required_cols = ['Guest Name', 'Adults', 'Children'] missing_cols = [col for col in required_cols if col not in df.columns] if missing_cols: error_preview = create_pdf_viewer(None) return None, error_preview, f"❌ Missing required CSV columns: {', '.join(missing_cols)}\n\n**Found columns:** {', '.join(df.columns)}\n\n**Required:** Guest Name, Confirmation No, Adults, Children" # Cap at 100 rows β€” keeps PDF generation within memory/time limits if len(df) > 100: print(f"WARNING: CSV has {len(df)} rows, capping at 100") df = df.iloc[:100] total = len(df) # Parse dates from form checkin = parse_date(checkin_date) if isinstance(checkin_date, str) else checkin_date checkout = parse_date(checkout_date) if isinstance(checkout_date, str) else checkout_date if not checkin: checkin = datetime.now().date() if not checkout: checkout = checkin + timedelta(days=1) # VALIDATION: Check-out must be after check-in if checkout <= checkin: return None, error_preview, "❌ Error: Check-out date must be after check-in date" # VALIDATION: Cancellation date must be before check-in (for Free Cancellation policy) if policy == "Free Cancellation" and cancellation_days: try: days = int(cancellation_days) cancellation_deadline = checkin - timedelta(days=days) if cancellation_deadline >= checkin: return None, error_preview, "❌ Error: Cancellation deadline must be before check-in date" except: pass # Use the provided number_of_nights if valid, otherwise calculate if number_of_nights and int(number_of_nights) >= 1: nights = int(number_of_nights) else: nights = (checkout - checkin).days if nights < 1: nights = 1 # Build booking data from form (common for all vouchers) booking_data = { "hotel": hotel_name, "checkin": checkin, "checkout": checkout, "room_type": room_type_select, "room_size": room_size or "", "meal_plan": meal_plan, "remarks": remarks or "", "cancellation": policy, "cancellation_days": int(cancellation_days) if policy == "Free Cancellation" and cancellation_days else None, "nights": nights } hotel_info = { "address_line1": address_line1 or "", "address_line2": address_line2 or "", "phone": phone or "" } # Fetch images once (same for all vouchers) progress(0.1, desc=f"πŸ–ΌοΈ Fetching hotel images...") images = fetch_hotel_images(hotel_name, city) logo_path = "logo.png" if os.path.exists("logo.png") else None # Build rooms list from ALL CSV rows all_rooms = [] progress(0.2, desc=f"πŸ“Š Processing {total} guests...") def _safe_int(val, default): """Safely convert "2", "2.0", 2, 2.0 β†’ int, no matter the source.""" try: return max(0, int(float(str(val).strip()))) except Exception: return default for idx, row in df.iterrows(): try: pct = 0.2 + 0.3 * (idx / max(total, 1)) if idx % 10 == 0: progress(pct, desc=f"πŸ“Š Processing guest {idx+1}/{total}...") guest_name = str(row.get('Guest Name', 'Unknown Guest')) conf_no = row.get('Confirmation No', '') # Normalise: NaN / None / "nan" / "none" β†’ empty string try: if conf_no is None or (isinstance(conf_no, float) and pd.isna(conf_no)): conf_no = "" else: conf_no = str(conf_no).strip() if conf_no.lower() in ('nan', 'none', ''): conf_no = "" except Exception: conf_no = "" room_data = { "guest": guest_name, "conf": conf_no, "adults": _safe_int(row.get('Adults', 2), 2), "children": _safe_int(row.get('Children', 0), 0) } all_rooms.append(room_data) except Exception as e: # Skip invalid rows but log the error print(f"Warning: Skipped row {idx+1} due to error: {str(e)}") continue if not all_rooms: error_preview = create_pdf_viewer(None) return None, error_preview, "❌ **No valid guest data found in CSV**" # Generate single multi-page PDF with all rooms progress(0.5, desc=f"πŸ“„ Generating multi-page PDF ({len(all_rooms)} pages)...") try: voucher_pdf = generate_voucher_pdf( booking_data=booking_data, hotel_info=hotel_info, rooms=all_rooms, # Pass ALL rooms for multi-page PDF image_urls=images, logo_path=logo_path ) # Save PDF - Use custom filename if provided if pdf_filename and pdf_filename.strip(): filename = pdf_filename.strip() if not filename.endswith('.pdf'): filename += '.pdf' else: safe_hotel_name = re.sub(r'[^\w\-]', '_', hotel_name) timestamp = datetime.now().strftime('%Y%m%d_%H%M%S') filename = f"{safe_hotel_name}_AllVouchers_{timestamp}.pdf" output_path = os.path.join(OUTPUT_DIR, filename) with open(output_path, 'wb') as f: f.write(voucher_pdf) # Log to Supabase (upload PDF + insert database record) supabase_result = log_and_upload_voucher( booking_data=booking_data, hotel_info=hotel_info, rooms=all_rooms, pdf_bytes=voucher_pdf, pdf_filename=filename, tab_source="Bulk CSV", city=city, is_bulk=True ) progress(1.0, desc=f"βœ… Complete!") # Create preview preview_html = create_pdf_viewer(output_path) summary = f""" ### πŸŽ‰ Processing Complete! **Hotel:** {hotel_name} **Dates:** {checkin.strftime('%d %b %Y')} - {checkout.strftime('%d %b %Y')} ({nights} nights) **Summary:** - βœ… **Generated:** {len(all_rooms)} voucher pages in ONE PDF - πŸ“„ **File:** {pdf_filename} - πŸ“Š **Total Guests:** {len(all_rooms)} **Guest List:** """ for i, room in enumerate(all_rooms, 1): summary += f"\n{i}. {room['guest']} - Conf: {room['conf'] or 'N/A'} - {room['adults']} Adults, {room['children']} Children" # Add Supabase status to summary if supabase_result["success"]: summary += f"\n\n{supabase_result['message']}" else: summary += f"\n\n⚠️ Supabase logging failed: {supabase_result['error']}" return output_path, preview_html, summary except Exception as e: import traceback traceback.print_exc() error_preview = create_pdf_viewer(None) return None, error_preview, f"❌ **Error generating PDF:** {str(e)}" except Exception as e: import traceback traceback.print_exc() error_preview = create_pdf_viewer(None) return None, error_preview, f"Error processing CSV: {str(e)}" def calculate_cancellation_date(checkin_date, cancellation_days): """ Calculate cancellation deadline date from check-in date and days before. Returns (date_string, warning_message) Args: checkin_date: datetime.date or string cancellation_days: int, days before check-in Returns: tuple: (date_string, warning_message) """ if not checkin_date: return "", "" if not cancellation_days: return "", "" # Parse checkin if it's a string if isinstance(checkin_date, str): checkin = parse_date(checkin_date) elif isinstance(checkin_date, datetime): checkin = checkin_date.date() else: checkin = checkin_date if not checkin: return "", "" try: days = int(float(cancellation_days)) # Handle float input # Validation if days < 1: return "", "## ⚠️ Warning\n**Days must be at least 1**" if days > 365: return "", "## ⚠️ Warning\n**Days cannot exceed 365**" cancellation_deadline = checkin - timedelta(days=days) return cancellation_deadline.strftime("%Y-%m-%d"), "" except (ValueError, TypeError): return "", "## ⚠️ Warning\n**Invalid number entered**" def calculate_cancellation_days(checkin_date, cancellation_date): """ Calculate days before check-in from cancellation deadline date. Returns (days, warning_message) Args: checkin_date: datetime.date or string cancellation_date: datetime.date or string Returns: tuple: (days, warning_message) """ if not checkin_date or not cancellation_date: return 7, "" # Parse checkin if it's a string if isinstance(checkin_date, str): checkin = parse_date(checkin_date) elif isinstance(checkin_date, datetime): checkin = checkin_date.date() else: checkin = checkin_date # Parse cancellation date if it's a string if isinstance(cancellation_date, str): cancel = parse_date(cancellation_date) elif isinstance(cancellation_date, datetime): cancel = cancellation_date.date() else: cancel = cancellation_date if not checkin or not cancel: return 7, "" try: days = (checkin - cancel).days # Validation: Cancellation must be before check-in if days < 1: return 7, "## ❌ Invalid Cancellation Policy\n**Cancellation deadline must be before check-in date**" if days > 365: return 7, "## ⚠️ Warning\n**Days cannot exceed 365**" return days, "" except (ValueError, TypeError): return 7, "⚠️ Invalid date" def update_cancellation_visibility(policy_value): """Show both cancellation inputs when Free Cancellation is selected.""" is_visible = (policy_value == "Free Cancellation") return ( gr.update(visible=is_visible), # cancellation_days gr.update(visible=is_visible) # cancellation_date ) def build_ag_grid_html(df): """ Build an iframe srcdoc containing a full AG Grid Community page. The grid is editable and supports Excel-style multi-cell paste. Data is synced back to the parent Gradio page via window.parent.postMessage. The FLATPICKR_JS listener in the parent writes it to the hidden textbox. """ import json as _json import uuid as _uuid # Use df.to_json so NaN β†’ null (valid JSON); json.dumps makes NaN β†’ NaN which # is invalid JSON and causes a silent SyntaxError that kills the whole script. rows_json = df.to_json(orient='records', force_ascii=False) columns = df.columns.tolist() cols_json = _json.dumps(columns) header_cells = "".join( f'<th>{c}&nbsp;<span class="col-sel-btn" data-ci="{i}" title="Select column (then Delete/Backspace to clear, or paste to fill)">&#9660;</span></th>' for i, c in enumerate(columns) ) # Zero-dependency inline HTML table β€” no CDN, no CSP issues. # Supports contenteditable cells, Excel-style multi-row paste, # and postMessage sync back to the Gradio parent page. html = f"""<!DOCTYPE html> <html><head><meta charset="utf-8"> <style> *{{box-sizing:border-box;margin:0;padding:0}} html,body{{height:100%;background:#111827;font-family:'Segoe UI',system-ui,sans-serif;overflow:auto}} .wrap{{overflow:auto;height:100%}} table{{width:100%;border-collapse:collapse;font-size:13px}} thead th{{ background:#1f2937;color:#818cf8;padding:8px 10px; text-align:left;font-weight:600;border-bottom:2px solid #374151; position:sticky;top:0;z-index:10;white-space:nowrap;user-select:none }} tbody tr{{border-bottom:1px solid #1f2937;transition:background .1s}} tbody tr:nth-child(even){{background:#0f172a}} tbody tr:hover{{background:#1e2a3a}} td{{ padding:5px 10px;color:#c7d2fe;border-right:1px solid #1f2937; min-width:90px;max-width:280px;white-space:nowrap;overflow:hidden; text-overflow:ellipsis;outline:none }} td:focus{{ outline:2px solid #6366f1;background:#1e1b4b; white-space:normal;overflow:visible; box-shadow:inset 0 0 0 1px #818cf8 }} .rn{{ color:#4b5563;background:#111827;text-align:center; min-width:34px;width:34px;padding:5px 4px;user-select:none }} .col-sel-btn{{ cursor:pointer;font-size:10px;color:#818cf8;opacity:0.45; margin-left:4px;user-select:none;transition:opacity .15s,color .15s; display:inline-block;vertical-align:middle }} .col-sel-btn:hover{{opacity:1;color:#c4b5fd}} .col-sel-btn.active{{opacity:1;color:#a5b4fc;text-shadow:0 0 6px #6366f1}} td.col-selected{{background:#1e1b4b !important;outline:1px solid #818cf8}} </style> </head> <body> <div class="wrap"> <table> <thead><tr><th class="rn">#</th>{header_cells}</tr></thead> <tbody id="tb"></tbody> </table> </div> <script> (function(){{ var cols = {cols_json}; var rows = {rows_json}; window.gridRows = rows; // exposed so parent can read synchronously var selectedCol = null; function selectColumn(ci){{ document.querySelectorAll('.col-sel-btn').forEach(function(b){{b.classList.remove('active');}}); if(selectedCol === ci){{selectedCol=null;build();return;}} selectedCol = ci; var btns = document.querySelectorAll('.col-sel-btn'); if(btns[ci]) btns[ci].classList.add('active'); build(); // Focus the table so keyboard events are captured var first = document.querySelector('#tb tr td.col-selected'); if(first) first.focus(); }} // β–Ό arrow click β€” event delegation so no global scope needed document.addEventListener('click', function(evt){{ var btn = evt.target.closest('.col-sel-btn'); if(!btn) return; evt.stopPropagation(); selectColumn(+btn.dataset.ci); }}); // Delete / Backspace clears the selected column document.addEventListener('keydown', function(evt){{ if(selectedCol === null) return; if(evt.key !== 'Delete' && evt.key !== 'Backspace') return; var active = document.activeElement; // Only intercept when a col-selected cell (or nothing editable) has focus if(active && active.contentEditable === 'true' && !active.classList.contains('col-selected')) return; evt.preventDefault(); var colName = cols[selectedCol]; rows.forEach(function(row){{row[colName] = '';}}); build(); sync(); // Re-focus first cell so user stays in the column var first = document.querySelector('#tb tr td.col-selected'); if(first) first.focus(); }}); function build(){{ var tb = document.getElementById('tb'); tb.innerHTML = ''; rows.forEach(function(row, ri){{ var tr = document.createElement('tr'); var rn = document.createElement('td'); rn.className = 'rn'; rn.textContent = ri+1; tr.appendChild(rn); cols.forEach(function(col, ci){{ var td = document.createElement('td'); td.contentEditable = 'true'; td.textContent = (row[col]!==null && row[col]!==undefined) ? String(row[col]) : ''; td.dataset.r = ri; td.dataset.c = col; if(selectedCol === ci) td.classList.add('col-selected'); td.addEventListener('input', function(){{ rows[+this.dataset.r][this.dataset.c] = (this.innerText||this.textContent).replace(/\\n/g,'').trim(); sync(); }}); tr.appendChild(td); }}); tb.appendChild(tr); }}); }} function sync(){{ var data = JSON.stringify(rows); // Direct synchronous call when same-origin (avoids postMessage async race) try{{ if(typeof window.parent.receiveGridData === 'function'){{ window.parent.receiveGridData(data); return; }} }}catch(e){{}} window.parent.postMessage({{type:'csvGridData', data:data}}, '*'); }} // Paste handler: column-fill mode OR normal multi-row paste document.addEventListener('paste', function(evt){{ var active = document.activeElement; if(!active || active.tagName !== 'TD') return; var text = (evt.clipboardData||window.clipboardData).getData('text'); var clipRows = text.split(/\\r?\\n/).filter(function(r){{return r.trim()!==''}}); if(!clipRows.length) return; if(selectedCol !== null){{ // Column-fill: paste fills the selected column from row 0 downward evt.preventDefault(); var colName = cols[selectedCol]; clipRows.forEach(function(rowStr, ri){{ var val = rowStr.split('\t')[0].trim(); if(ri < rows.length) rows[ri][colName] = val; }}); build(); sync(); return; }} // Normal multi-row paste (existing behaviour) if(!active.dataset.r || clipRows.length <= 1) return; evt.preventDefault(); var sr = +active.dataset.r; var sc = cols.indexOf(active.dataset.c); clipRows.forEach(function(rowStr, ri){{ var cells = rowStr.split('\t'); var rIdx = sr + ri; if(rIdx >= rows.length) return; cells.forEach(function(val, ci){{ var cIdx = sc + ci; if(cIdx < cols.length) rows[rIdx][cols[cIdx]] = val.trim(); }}); }}); build(); sync(); }}); build(); setTimeout(sync, 300); }})(); </script> </body></html>""" 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'<iframe src="/gradio_api/file={url_path}" style="width:100%;height:420px;border:1px solid #333;border-radius:8px;" allow="clipboard-read; clipboard-write"></iframe>' 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 <script> tags). # --------------------------------------------------------------------------- FLATPICKR_JS = """ (() => { var FP_CSS = 'https://cdn.jsdelivr.net/npm/flatpickr/dist/flatpickr.min.css'; var FP_JS = 'https://cdn.jsdelivr.net/npm/flatpickr'; var TAB_IDS = ['search', 'pdf', 'bulk']; var _fp = {}; function loadCSS(href) { if (document.querySelector('link[href="' + href + '"]')) return; var l = document.createElement('link'); l.rel = 'stylesheet'; l.href = href; document.head.appendChild(l); } function loadScript(src, cb) { if (typeof flatpickr !== 'undefined') { cb(); return; } var s = document.createElement('script'); s.src = src; s.onload = cb; document.head.appendChild(s); } function getInp(eid) { var el = document.getElementById(eid); if (!el) return null; return el.querySelector('textarea') || el.querySelector('input'); } function setGradio(eid, val) { var inp = getInp(eid); if (!inp) return; var proto = inp.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; var d = Object.getOwnPropertyDescriptor(proto, 'value'); if (d && d.set) d.set.call(inp, val); else inp.value = val; inp.dispatchEvent(new Event('input', {bubbles: true})); inp.dispatchEvent(new Event('change', {bubbles: true})); } function initPicker(tabId) { var el = document.getElementById('dr-' + tabId); if (!el) return false; // Detect stale instance (element was re-rendered by Gradio): destroy & reinit if (_fp[tabId]) { if (_fp[tabId].element === el || el.classList.contains('flatpickr-input')) return true; try { _fp[tabId].destroy(); } catch(e) {} _fp[tabId] = null; } _fp[tabId] = flatpickr(el, { mode: 'range', dateFormat: 'Y-m-d', showMonths: 2, disableMobile: true, monthSelectorType: 'static', onChange: function(dates, str, inst) { if (dates.length === 2) { var ci = inst.formatDate(dates[0], 'Y-m-d'); var co = inst.formatDate(dates[1], 'Y-m-d'); inst.close(); setGradio('checkin-' + tabId, ci); setTimeout(function() { setGradio('checkout-' + tabId, co); }, 80); } } }); // Bidirectional sync: when Python sets textbox values, update the visual picker. // Guard: skip while the calendar is open to avoid fighting the user's selection. var prevCi = '', prevCo = ''; setInterval(function() { if (!_fp[tabId] || _fp[tabId].isOpen) return; var ci = (getInp('checkin-' + tabId) || {}).value || ''; var co = (getInp('checkout-' + tabId) || {}).value || ''; if (ci === prevCi && co === prevCo) return; prevCi = ci; prevCo = co; if (ci && co) _fp[tabId].setDate([ci, co], false); else if (ci) _fp[tabId].setDate([ci], false); else _fp[tabId].clear(false); }, 600); return true; } function tryInitAll() { TAB_IDS.forEach(function(id) { try { initPicker(id); } catch(e) {} }); // Stop retrying only when all three pickers are confirmed initialised. // Tabs 2 & 3 are lazy-rendered, so they may not exist until first clicked. var allDone = TAB_IDS.every(function(id) { return !!_fp[id]; }); if (!allDone) setTimeout(tryInitAll, 500); } // Also inject Flatpickr theme CSS for range highlight colours var style = document.createElement('style'); style.textContent = [ '.flatpickr-day.inRange{background:rgba(99,102,241,.25)!important;border-color:rgba(99,102,241,.25)!important;}', '.flatpickr-day.startRange,.flatpickr-day.endRange,', '.flatpickr-day.startRange:hover,.flatpickr-day.endRange:hover{', 'background:#6366f1!important;border-color:#6366f1!important;}' ].join(''); document.head.appendChild(style); // ── Synchronous entry-point called directly by same-origin iframe ── // Falls back to postMessage listener below for cross-origin cases. window.receiveGridData = function(data) { setGradio('csv-grid-data', data); }; // ── postMessage listener: fallback for cross-origin / older iframe ── window.addEventListener('message', function(evt) { if (!evt.data || evt.data.type !== 'csvGridData') return; var container = document.getElementById('csv-grid-data'); if (!container) return; var ta = container.querySelector('textarea') || container.querySelector('input'); if (!ta) return; var proto = ta.tagName === 'TEXTAREA' ? HTMLTextAreaElement.prototype : HTMLInputElement.prototype; var desc = Object.getOwnPropertyDescriptor(proto, 'value'); if (desc && desc.set) desc.set.call(ta, evt.data.data); else ta.value = evt.data.data; ta.dispatchEvent(new Event('input', {bubbles: true})); ta.dispatchEvent(new Event('change', {bubbles: true})); }); loadCSS(FP_CSS); loadScript(FP_JS, tryInitAll); })(); """ # Build Gradio interface with gr.Blocks(title="Odaduu Voucher Generator") as demo: gr.Markdown("# Odaduu Voucher Generator") with gr.Tabs(): # ===== TAB 1: SEARCH HOTEL ===== with gr.Tab("πŸ” Search Hotel"): # Status bar at top status_text = gr.Markdown("") # ===== TOP SECTION: Form Fields ===== with gr.Row(): # LEFT COLUMN - Hotel & Booking Details with gr.Column(scale=1): # Hotel Search Section gr.Markdown("## πŸ” Find Your Hotel") with gr.Row(): search_query = gr.Textbox(label="Search Hotel", placeholder="e.g., Taj Mumbai", scale=3) search_btn = gr.Button("Search", variant="secondary", scale=1) hotel_select = gr.Dropdown( label="Select Hotel Name", choices=[], interactive=True, allow_custom_value=True, info="Search and select hotel" ) hotel_name = gr.Textbox( label="Hotel Name", placeholder="Auto-filled from hotel search", info="Edit if needed before generating" ) city = gr.Textbox(label="City") # Address (populated via Maps grounding) gr.Markdown("### Address (auto-fetched)") address_line1 = gr.Textbox(label="Address Line 1") address_line2 = gr.Textbox(label="Address Line 2") phone = gr.Textbox(label="Phone") # RIGHT COLUMN - Booking Details with gr.Column(scale=1): gr.Markdown("## πŸ“… Stay Details") gr.HTML(make_date_range_html("search")) with gr.Row(): checkin_date = gr.Textbox(label="Check-in Date", elem_id="checkin-search", placeholder="YYYY-MM-DD") checkout_date = gr.Textbox(label="Check-out Date", elem_id="checkout-search", placeholder="YYYY-MM-DD") number_of_nights = gr.Number(label="Nights", value=1, minimum=1, precision=0) with gr.Row(): room_type_select = gr.Dropdown( label="Room Type", choices=["Standard", "Deluxe", "Superior", "Suite", "Executive"], value="Standard", allow_custom_value=True, info="Auto-populated from hotel data" ) room_size = gr.Textbox(label="Room Size (e.g. 35 sqm)") meal_plan = gr.Dropdown( label="Meal Plan", choices=["Breakfast Only", "Room Only", "Half Board", "Full Board"], value="Breakfast Only" ) remarks = gr.Textbox(label="Remarks (Optional)", lines=2) policy = gr.Radio( label="Policy", choices=["Non-Refundable", "Free Cancellation"], value="Non-Refundable" ) with gr.Row(): cancellation_days = gr.Number( label="Days before check-in", value=7, minimum=1, maximum=365, precision=0, visible=False, info="Number of days before check-in" ) cancellation_date = gr.DateTime( label="Cancellation deadline", include_time=False, type="string", value=None, visible=False, info="Or select a specific deadline date" ) # ===== GUEST TABLE - Full Width ===== gr.Markdown("---") gr.Markdown("## πŸ‘₯ Guest Information") guest_table = gr.Dataframe( headers=["Guest Name", "Confirmation No", "Adults", "Children"], datatype=["str", "str", "number", "number"], row_count=(1, "dynamic"), column_count=(4, "fixed"), label="Guest Details (editable)", interactive=True, value=[["", "", 0, 0]] # Default with 0 adults/children ) selected_row_search = gr.State(-1) with gr.Row(): add_guest_btn = gr.Button("+ Add Guest Row", size="sm", variant="secondary") delete_guest_btn = gr.Button("πŸ—‘ Delete Row", size="sm", variant="secondary") # PDF Filename Field gr.Markdown("---") gr.Markdown("## πŸ“ PDF Filename") pdf_filename = gr.Textbox( label="PDF Filename", placeholder="Hotel_Name-ConfirmationNo.pdf", value="", interactive=True, info="Customize the filename for the generated PDF" ) # Generate Button - Full Width generate_btn = gr.Button("Generate Voucher", variant="primary", size="lg") # ===== BOTTOM SECTION: PDF Preview and Download ===== gr.Markdown("---") gr.Markdown("### Preview & Download") with gr.Row(): with gr.Column(scale=2): # Download link download_file = gr.File( label="πŸ“₯ Download PDF", type="filepath", interactive=False, show_label=True ) # PDF Preview area using HTML pdf_preview_html = gr.HTML( value='<div style="height:600px;background:#2a2a3e;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#888;font-size:18px;">πŸ“„ Preview will appear here after generation</div>', label="Preview" ) with gr.Column(scale=1): gr.Markdown(""" ### πŸ’‘ How to View **Option 1: Quick Preview** ⭐ - See PDF in preview area (left) - Scroll to view full document **Option 2: New Tab** - Click filename above - Opens in browser for full quality **Option 3: Download** - Click download icon - Save to your device """) # ===== TAB 2: PDF EXTRACTION ===== with gr.Tab("πŸ“„ PDF Extraction"): # Status bar at top status_text_pdf = gr.Markdown("") # PDF Upload Section gr.Markdown("## πŸ“€ Upload Booking PDF") with gr.Row(): pdf_input = gr.File( label="Upload PDF", file_types=[".pdf"], type="filepath" ) extract_btn = gr.Button("Extract Data", variant="secondary") gr.Markdown("---") # ===== FORM FIELDS ===== with gr.Row(): # LEFT COLUMN - Hotel Information with gr.Column(scale=1): gr.Markdown("## 🏨 Hotel Information") hotel_name_pdf = gr.Textbox( label="Hotel Name", placeholder="Enter hotel name or extract from PDF", info="Edit if needed after extraction" ) city_pdf = gr.Textbox(label="City") gr.Markdown("### Address") address_line1_pdf = gr.Textbox(label="Address Line 1") address_line2_pdf = gr.Textbox(label="Address Line 2") phone_pdf = gr.Textbox(label="Phone") # RIGHT COLUMN - Booking Details with gr.Column(scale=1): gr.Markdown("## πŸ“… Stay Details") gr.HTML(make_date_range_html("pdf")) with gr.Row(): checkin_date_pdf = gr.Textbox(label="Check-in Date", elem_id="checkin-pdf", placeholder="YYYY-MM-DD") checkout_date_pdf = gr.Textbox(label="Check-out Date", elem_id="checkout-pdf", placeholder="YYYY-MM-DD") number_of_nights_pdf = gr.Number(label="Nights", value=1, minimum=1, precision=0) with gr.Row(): room_type_select_pdf = gr.Dropdown( label="Room Type", choices=["Standard", "Deluxe", "Superior", "Suite", "Executive"], value="Standard", allow_custom_value=True, info="Editable after PDF extraction" ) room_size_pdf = gr.Textbox(label="Room Size (e.g. 35 sqm)") meal_plan_pdf = gr.Dropdown( label="Meal Plan", choices=["Breakfast Only", "Room Only", "Half Board", "Full Board"], value="Breakfast Only" ) remarks_pdf = gr.Textbox(label="Remarks (Optional)", lines=2) policy_pdf = gr.Radio( label="Policy", choices=["Non-Refundable", "Free Cancellation"], value="Non-Refundable" ) with gr.Row(): cancellation_days_pdf = gr.Number( label="Days before check-in", value=7, minimum=1, maximum=365, precision=0, visible=False, info="Number of days before check-in" ) cancellation_date_pdf = gr.DateTime( label="Cancellation deadline", include_time=False, type="string", value=None, visible=False, info="Or select a specific deadline date" ) # ===== GUEST TABLE - Full Width ===== gr.Markdown("---") gr.Markdown("## πŸ‘₯ Guest Information") guest_table_pdf = gr.Dataframe( headers=["Guest Name", "Confirmation No", "Adults", "Children"], datatype=["str", "str", "number", "number"], row_count=(1, "dynamic"), column_count=(4, "fixed"), label="Guest Details (editable)", interactive=True, value=[["", "", 0, 0]] ) selected_row_pdf = gr.State(-1) with gr.Row(): add_guest_btn_pdf = gr.Button("+ Add Guest Row", size="sm", variant="secondary") delete_guest_btn_pdf = gr.Button("πŸ—‘ Delete Row", size="sm", variant="secondary") # PDF Filename Field gr.Markdown("---") gr.Markdown("## πŸ“ PDF Filename") pdf_filename_pdf = gr.Textbox( label="PDF Filename", placeholder="Hotel_Name-ConfirmationNo.pdf", value="", interactive=True, info="Customize the filename for the generated PDF" ) # Generate Button - Full Width generate_btn_pdf = gr.Button("Generate Voucher", variant="primary", size="lg") # ===== BOTTOM SECTION: PDF Preview and Download ===== gr.Markdown("---") gr.Markdown("### Preview & Download") with gr.Row(): with gr.Column(scale=2): # Download link download_file_pdf = gr.File( label="πŸ“₯ Download PDF", type="filepath", interactive=False, show_label=True ) # PDF Preview area using HTML pdf_preview_html_pdf = gr.HTML( value='<div style="height:600px;background:#2a2a3e;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#888;font-size:18px;">πŸ“„ Preview will appear here after generation</div>', label="Preview" ) with gr.Column(scale=1): gr.Markdown(""" ### πŸ’‘ How to View **Option 1: Quick Preview** ⭐ - See PDF in preview area (left) - Scroll to view full document **Option 2: New Tab** - Click filename above - Opens in browser for full quality **Option 3: Download** - Click download icon - Save to your device """) # ===== TAB 3: BULK CSV PROCESSING ===== with gr.Tab("πŸ“Š Bulk CSV Processing"): gr.Markdown(""" ## πŸš€ Bulk Voucher Generation Fill in booking details once, upload guest list CSV, generate one multi-page PDF with all vouchers! """) # Status bar at top status_text_bulk = gr.Markdown("") # ===== TOP SECTION: Form Fields ===== with gr.Row(): # LEFT COLUMN - Hotel & Booking Details with gr.Column(scale=1): # Hotel Search Section gr.Markdown("## πŸ” Find Your Hotel") with gr.Row(): search_query_bulk = gr.Textbox(label="Search Hotel", placeholder="e.g., Taj Mumbai", scale=3) search_btn_bulk = gr.Button("Search", variant="secondary", scale=1) hotel_select_bulk = gr.Dropdown( label="Select Hotel Name", choices=[], interactive=True, allow_custom_value=True, info="Search and select hotel" ) hotel_name_bulk = gr.Textbox( label="Hotel Name", placeholder="Search and select hotel above", info="Auto-filled from hotel search" ) city_bulk = gr.Textbox(label="City") # Address (populated via Maps grounding) gr.Markdown("### Address (auto-fetched)") address_line1_bulk = gr.Textbox(label="Address Line 1") address_line2_bulk = gr.Textbox(label="Address Line 2") phone_bulk = gr.Textbox(label="Phone") # RIGHT COLUMN - Booking Details with gr.Column(scale=1): gr.Markdown("## πŸ“… Stay Details") gr.HTML(make_date_range_html("bulk")) with gr.Row(): checkin_date_bulk = gr.Textbox(label="Check-in Date", elem_id="checkin-bulk", placeholder="YYYY-MM-DD") checkout_date_bulk = gr.Textbox(label="Check-out Date", elem_id="checkout-bulk", placeholder="YYYY-MM-DD") number_of_nights_bulk = gr.Number(label="Nights", value=1, minimum=1, precision=0) with gr.Row(): room_type_select_bulk = gr.Dropdown( label="Room Type", choices=["Standard", "Deluxe", "Superior", "Suite", "Executive"], value="Standard", allow_custom_value=True, info="Auto-populated from hotel data" ) room_size_bulk = gr.Textbox(label="Room Size (e.g. 35 sqm)") meal_plan_bulk = gr.Dropdown( label="Meal Plan", choices=["Breakfast Only", "Room Only", "Half Board", "Full Board"], value="Breakfast Only" ) remarks_bulk = gr.Textbox(label="Remarks (Optional)", lines=2) policy_bulk = gr.Radio( label="Policy", choices=["Non-Refundable", "Free Cancellation"], value="Non-Refundable" ) with gr.Row(): cancellation_days_bulk = gr.Number( label="Days before check-in", value=7, minimum=1, maximum=365, precision=0, visible=False, info="Number of days before check-in" ) cancellation_date_bulk = gr.DateTime( label="Cancellation deadline", include_time=False, type="string", value=None, visible=False, info="Or select a specific deadline date" ) # ===== CSV UPLOAD SECTION ===== gr.Markdown("---") gr.Markdown(""" ## πŸ“„ Upload Guest List CSV **CSV should contain these columns (flexible naming):** - `Guest Name` / `GUESTS NAME` - Full name(s) of guest(s) (use comma or semicolon for multiple) - `Confirmation No` / `CONFIRMATION NO.` - Booking confirmation number (can be blank) - `Adults` / `ADULTS` - Number of adults (e.g., 2) - `Children` / `CHILD` / `CHILDREN` - Number of children (e.g., 0) **Example CSV:** ```csv GUESTS NAME,CONFIRMATION NO.,ADULTS,CHILD PRACHI SINGH, ANANYA SINGH,1234,2,0 AJAY KUMAR GUPTA, POOJA GUPTA,1238,2,0 ``` **Note:** Each row becomes one page in the final PDF. All vouchers will be in a single file. """) bulk_csv_input = gr.File( label="Upload Guest List CSV", file_types=[".csv"], type="filepath" ) # CSV Preview β€” AG Grid rendered inside gr.HTML csv_ag_grid_html = gr.HTML( value="", visible=False ) # Hidden textbox to store AG Grid data as JSON (bridge JS ↔ Python) csv_grid_data = gr.Textbox( value="", visible=False, elem_id="csv-grid-data" ) csv_preview_info = gr.Markdown( "", visible=False ) # PDF Filename Field gr.Markdown("---") gr.Markdown("## πŸ“ PDF Filename") pdf_filename_bulk = gr.Textbox( label="PDF Filename", placeholder="Hotel_Name_AllVouchers_YYYYMMDD_HHMMSS.pdf", value="", interactive=True, info="Customize the filename for the generated multi-page PDF" ) bulk_csv_btn = gr.Button("🎯 Generate Multi-Page Voucher", variant="primary", size="lg") # ===== BOTTOM SECTION: PDF Preview and Download ===== gr.Markdown("---") gr.Markdown("### Preview & Download") with gr.Row(): with gr.Column(scale=2): # Download link bulk_csv_output = gr.File( label="πŸ“₯ Download PDF (All Vouchers)", type="filepath", interactive=False, show_label=True ) # PDF Preview area using HTML bulk_pdf_preview_html = gr.HTML( value='<div style="height:600px;background:#2a2a3e;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#888;font-size:18px;">πŸ“„ Preview will appear here after generation</div>', label="Preview" ) with gr.Column(scale=1): gr.Markdown(""" ### πŸ’‘ How to View **Option 1: Quick Preview** ⭐ - See PDF in preview area (left) - Scroll to view all pages **Option 2: New Tab** - Click filename above - Opens in browser for full quality **Option 3: Download** - Click download icon - Save to your device """) bulk_csv_status = gr.Markdown("") # ===== EVENT HANDLERS ===== # PDF Extraction Tab extract_btn.click( fn=extract_from_pdf, inputs=[pdf_input], outputs=[ hotel_name_pdf, city_pdf, checkin_date_pdf, checkout_date_pdf, number_of_nights_pdf, room_type_select_pdf, room_size_pdf, meal_plan_pdf, remarks_pdf, address_line1_pdf, address_line2_pdf, phone_pdf, guest_table_pdf, status_text_pdf ] ) # ── Search Hotel Tab ────────────────────────────────────────────────────── search_btn.click( fn=search_hotels, inputs=[search_query], outputs=[hotel_select] ) hotel_select.change( fn=on_hotel_selected, inputs=[hotel_select], outputs=[hotel_name, city, address_line1, address_line2, phone, room_type_select] ) def on_date_change_search(ci, co, cancel_days): nights, warning = calculate_nights(ci, co) cancel_dt, _ = calculate_cancellation_date(ci, cancel_days) return nights, warning if warning else "", cancel_dt checkin_date.change( fn=on_date_change_search, inputs=[checkin_date, checkout_date, cancellation_days], outputs=[number_of_nights, status_text, cancellation_date] ) checkout_date.change( fn=on_date_change_search, inputs=[checkin_date, checkout_date, cancellation_days], outputs=[number_of_nights, status_text, cancellation_date] ) generate_btn.click( fn=generate_voucher_search_tab, inputs=[ hotel_name, city, checkin_date, checkout_date, number_of_nights, room_type_select, room_size, meal_plan, remarks, policy, cancellation_days, guest_table, address_line1, address_line2, phone, pdf_filename ], outputs=[download_file, pdf_preview_html, status_text] ) def update_pdf_filename(hotel, guest_table_data): if not hotel: return "" conf_no = "" if guest_table_data is not None and len(guest_table_data) > 0: first_row = guest_table_data[0] if isinstance(guest_table_data, list) else guest_table_data.values.tolist()[0] if len(first_row) >= 2: conf_no = str(first_row[1]) if first_row[1] else "" return generate_default_filename(hotel, conf_no, is_bulk=False) hotel_name.change(fn=update_pdf_filename, inputs=[hotel_name, guest_table], outputs=[pdf_filename]) guest_table.change(fn=update_pdf_filename, inputs=[hotel_name, guest_table], outputs=[pdf_filename]) def add_guest_row(current_table): rows = current_table.values.tolist() if hasattr(current_table, 'values') else (current_table or []) rows = [r for r in rows if any(str(c).strip() for c in r)] # drop fully-blank rows rows.append(["", "", 0, 0]) return rows add_guest_btn.click(fn=add_guest_row, inputs=[guest_table], outputs=[guest_table]) def on_guest_table_select(evt: gr.SelectData): return evt.index[0] # row index of clicked cell guest_table.select(fn=on_guest_table_select, outputs=[selected_row_search]) def delete_guest_row(current_table, row_idx): rows = current_table.values.tolist() if hasattr(current_table, 'values') else (current_table or []) if 0 <= row_idx < len(rows): rows.pop(row_idx) if not rows: rows = [["", "", 0, 0]] return rows, -1 # reset selection after delete delete_guest_btn.click( fn=delete_guest_row, inputs=[guest_table, selected_row_search], outputs=[guest_table, selected_row_search] ) policy.change( fn=update_cancellation_visibility, inputs=[policy], outputs=[cancellation_days, cancellation_date] ) def update_cancel_date_from_days(ci, days, cur_dt): cancel_date, warning = calculate_cancellation_date(ci, days) # No-op if the date wouldn't actually change (breaks circular cascade) if cancel_date and cur_dt and parse_date(cancel_date) == parse_date(cur_dt): return gr.update(), warning if warning else "" return cancel_date, warning if warning else "" def update_cancel_days_from_date(ci, cancel_dt, cur_days): days, warning = calculate_cancellation_days(ci, cancel_dt) # No-op if days wouldn't change try: if int(cur_days or 0) == days: return gr.update(), warning if warning else "" except (ValueError, TypeError): pass return days, warning if warning else "" cancellation_days.change( fn=update_cancel_date_from_days, inputs=[checkin_date, cancellation_days, cancellation_date], outputs=[cancellation_date, status_text], show_progress=False ) cancellation_date.change( fn=update_cancel_days_from_date, inputs=[checkin_date, cancellation_date, cancellation_days], outputs=[cancellation_days, status_text], show_progress=False ) # ── PDF Extraction Tab ──────────────────────────────────────────────────── def on_date_change_pdf(ci, co, cancel_days): nights, warning = calculate_nights(ci, co) cancel_dt, _ = calculate_cancellation_date(ci, cancel_days) return nights, warning if warning else "", cancel_dt checkin_date_pdf.change( fn=on_date_change_pdf, inputs=[checkin_date_pdf, checkout_date_pdf, cancellation_days_pdf], outputs=[number_of_nights_pdf, status_text_pdf, cancellation_date_pdf] ) checkout_date_pdf.change( fn=on_date_change_pdf, inputs=[checkin_date_pdf, checkout_date_pdf, cancellation_days_pdf], outputs=[number_of_nights_pdf, status_text_pdf, cancellation_date_pdf] ) policy_pdf.change( fn=update_cancellation_visibility, inputs=[policy_pdf], outputs=[cancellation_days_pdf, cancellation_date_pdf] ) def update_cancel_date_from_days_pdf(ci, days, cur_dt): cancel_date, warning = calculate_cancellation_date(ci, days) if cancel_date and cur_dt and parse_date(cancel_date) == parse_date(cur_dt): return gr.update(), warning if warning else "" return cancel_date, warning if warning else "" def update_cancel_days_from_date_pdf(ci, cancel_dt, cur_days): days, warning = calculate_cancellation_days(ci, cancel_dt) try: if int(cur_days or 0) == days: return gr.update(), warning if warning else "" except (ValueError, TypeError): pass return days, warning if warning else "" cancellation_days_pdf.change( fn=update_cancel_date_from_days_pdf, inputs=[checkin_date_pdf, cancellation_days_pdf, cancellation_date_pdf], outputs=[cancellation_date_pdf, status_text_pdf], show_progress=False ) cancellation_date_pdf.change( fn=update_cancel_days_from_date_pdf, inputs=[checkin_date_pdf, cancellation_date_pdf, cancellation_days_pdf], outputs=[cancellation_days_pdf, status_text_pdf], show_progress=False ) generate_btn_pdf.click( fn=generate_voucher_pdf_tab, inputs=[ hotel_name_pdf, city_pdf, checkin_date_pdf, checkout_date_pdf, number_of_nights_pdf, room_type_select_pdf, room_size_pdf, meal_plan_pdf, remarks_pdf, policy_pdf, cancellation_days_pdf, guest_table_pdf, address_line1_pdf, address_line2_pdf, phone_pdf, pdf_filename_pdf ], outputs=[download_file_pdf, pdf_preview_html_pdf, status_text_pdf] ) def update_pdf_filename_pdf_tab(hotel, guest_table_data): if not hotel: return "" conf_no = "" if guest_table_data is not None and len(guest_table_data) > 0: first_row = guest_table_data[0] if isinstance(guest_table_data, list) else guest_table_data.values.tolist()[0] if len(first_row) >= 2: conf_no = str(first_row[1]) if first_row[1] else "" return generate_default_filename(hotel, conf_no, is_bulk=False) hotel_name_pdf.change(fn=update_pdf_filename_pdf_tab, inputs=[hotel_name_pdf, guest_table_pdf], outputs=[pdf_filename_pdf]) guest_table_pdf.change(fn=update_pdf_filename_pdf_tab, inputs=[hotel_name_pdf, guest_table_pdf], outputs=[pdf_filename_pdf]) def add_guest_row_pdf(current_table): rows = current_table.values.tolist() if hasattr(current_table, 'values') else (current_table or []) rows = [r for r in rows if any(str(c).strip() for c in r)] rows.append(["", "", 0, 0]) return rows add_guest_btn_pdf.click(fn=add_guest_row_pdf, inputs=[guest_table_pdf], outputs=[guest_table_pdf]) def on_guest_table_pdf_select(evt: gr.SelectData): return evt.index[0] guest_table_pdf.select(fn=on_guest_table_pdf_select, outputs=[selected_row_pdf]) def delete_guest_row_pdf(current_table, row_idx): rows = current_table.values.tolist() if hasattr(current_table, 'values') else (current_table or []) if 0 <= row_idx < len(rows): rows.pop(row_idx) if not rows: rows = [["", "", 0, 0]] return rows, -1 # reset selection after delete delete_guest_btn_pdf.click( fn=delete_guest_row_pdf, inputs=[guest_table_pdf, selected_row_pdf], outputs=[guest_table_pdf, selected_row_pdf] ) # ── Bulk CSV Tab ────────────────────────────────────────────────────────── search_btn_bulk.click( fn=search_hotels, inputs=[search_query_bulk], outputs=[hotel_select_bulk] ) def on_hotel_selected_bulk(selected_hotel): hotel_name, city, addr1, addr2, phone, room_type_update = on_hotel_selected(selected_hotel) filename = generate_default_filename(hotel_name, "", is_bulk=True) return hotel_name, city, addr1, addr2, phone, room_type_update, filename hotel_select_bulk.change( fn=on_hotel_selected_bulk, inputs=[hotel_select_bulk], outputs=[hotel_name_bulk, city_bulk, address_line1_bulk, address_line2_bulk, phone_bulk, room_type_select_bulk, pdf_filename_bulk] ) def on_date_change_bulk(ci, co, cancel_days): nights, warning = calculate_nights(ci, co) cancel_dt, _ = calculate_cancellation_date(ci, cancel_days) return nights, warning if warning else "", cancel_dt checkin_date_bulk.change( fn=on_date_change_bulk, inputs=[checkin_date_bulk, checkout_date_bulk, cancellation_days_bulk], outputs=[number_of_nights_bulk, bulk_csv_status, cancellation_date_bulk] ) checkout_date_bulk.change( fn=on_date_change_bulk, inputs=[checkin_date_bulk, checkout_date_bulk, cancellation_days_bulk], outputs=[number_of_nights_bulk, bulk_csv_status, cancellation_date_bulk] ) policy_bulk.change( fn=update_cancellation_visibility, inputs=[policy_bulk], outputs=[cancellation_days_bulk, cancellation_date_bulk] ) def update_cancel_date_from_days_bulk(ci, days, cur_dt): cancel_date, warning = calculate_cancellation_date(ci, days) if cancel_date and cur_dt and parse_date(cancel_date) == parse_date(cur_dt): return gr.update(), warning if warning else "" return cancel_date, warning if warning else "" def update_cancel_days_from_date_bulk(ci, cancel_dt, cur_days): days, warning = calculate_cancellation_days(ci, cancel_dt) try: if int(cur_days or 0) == days: return gr.update(), warning if warning else "" except (ValueError, TypeError): pass return days, warning if warning else "" cancellation_days_bulk.change( fn=update_cancel_date_from_days_bulk, inputs=[checkin_date_bulk, cancellation_days_bulk, cancellation_date_bulk], outputs=[cancellation_date_bulk, bulk_csv_status], show_progress=False ) cancellation_date_bulk.change( fn=update_cancel_days_from_date_bulk, inputs=[checkin_date_bulk, cancellation_date_bulk, cancellation_days_bulk], outputs=[cancellation_days_bulk, bulk_csv_status], show_progress=False ) bulk_csv_input.change( fn=preview_csv_upload, inputs=[bulk_csv_input], outputs=[csv_ag_grid_html, csv_preview_info, csv_grid_data] ) bulk_csv_btn.click( fn=process_bulk_csv, inputs=[ bulk_csv_input, csv_grid_data, hotel_name_bulk, city_bulk, checkin_date_bulk, checkout_date_bulk, number_of_nights_bulk, room_type_select_bulk, room_size_bulk, meal_plan_bulk, remarks_bulk, policy_bulk, cancellation_days_bulk, address_line1_bulk, address_line2_bulk, phone_bulk, pdf_filename_bulk ], outputs=[bulk_csv_output, bulk_pdf_preview_html, bulk_csv_status], # Read grid data synchronously from the iframe right before Python runs. # This bypasses any async postMessage lag and ensures edited cells # (e.g. confirmation numbers) are always included. js="""(v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13,v14,v15,v16) => { try { var frames = document.querySelectorAll('iframe'); for (var i = 0; i < frames.length; i++) { if (frames[i].src && frames[i].src.indexOf('ag_grid_') > -1) { try { if (frames[i].contentWindow && frames[i].contentWindow.gridRows) { v1 = JSON.stringify(frames[i].contentWindow.gridRows); break; } } catch(e) {} } } } catch(e) {} return [v0,v1,v2,v3,v4,v5,v6,v7,v8,v9,v10,v11,v12,v13,v14,v15,v16]; }""" ) def update_pdf_filename_bulk_tab(hotel): if not hotel: return "" return generate_default_filename(hotel, "", is_bulk=True) hotel_name_bulk.change( fn=update_pdf_filename_bulk_tab, inputs=[hotel_name_bulk], outputs=[pdf_filename_bulk] ) if __name__ == "__main__": # helper for huggingface spaces: enable queue for long running tasks demo.queue() # allowed_paths needed for /file= route to serve local files print(f"DEBUG: Allowed paths: {[OUTPUT_DIR]}") # Theme moved to launch() in Gradio 6 demo.launch( server_port=7860, allowed_paths=[OUTPUT_DIR], theme=gr.themes.Soft(primary_hue="blue", secondary_hue="orange"), js=FLATPICKR_JS )
"""
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 <script> tags.
The JS initialization is handled via demo.launch(js=FLATPICKR_JS).
"""
return f"""<div style="margin-bottom:4px;">
<style>
.dr-wrap-{tab_id} {{ position: relative; }}
.dr-wrap-{tab_id} input {{
width: 100%; padding: 8px 40px 8px 12px;
background: var(--input-background-fill, #1f2937);
border: 1px solid var(--input-border-color, #374151);
border-radius: 8px; color: var(--body-text-color, #f3f4f6);
font-size: 14px; cursor: pointer; box-sizing: border-box;
font-family: inherit; transition: border-color 0.15s;
}}
.dr-wrap-{tab_id} input:hover {{ border-color: #6366f1; outline: none; }}
.dr-wrap-{tab_id} input::placeholder {{ color: #9ca3af; }}
.dr-icon-{tab_id} {{
position: absolute; right: 10px; top: 50%;
transform: translateY(-50%); pointer-events: none; color: #9ca3af;
}}
</style>
<div class="dr-wrap-{tab_id}">
<input id="dr-{tab_id}" type="text" placeholder="Click to select check-in β†’ check-out" readonly>
<span class="dr-icon-{tab_id}">
<svg xmlns="http://www.w3.org/2000/svg" width="18" height="18" viewBox="0 0 24 24"
fill="none" stroke="currentColor" stroke-width="2"
stroke-linecap="round" stroke-linejoin="round">
<rect x="3" y="4" width="18" height="18" rx="2" ry="2"></rect>
<line x1="16" y1="2" x2="16" y2="6"></line>
<line x1="8" y1="2" x2="8" y2="6"></line>
<line x1="3" y1="10" x2="21" y2="10"></line>
</svg>
</span>
</div>
</div>"""
def create_pdf_viewer(pdf_path):
"""Create PDF preview by converting first page to image"""
if not pdf_path or not os.path.exists(pdf_path):
return '<div style="height:600px;background:#2a2a3e;border-radius:8px;display:flex;align-items:center;justify-content:center;color:#888;font-size:18px;">πŸ“„ Preview will appear here after generation</div>'
try:
import fitz # PyMuPDF
import base64
from io import BytesIO
from PIL import Image
# Get file info
file_size_kb = os.path.getsize(pdf_path) / 1024
file_name = os.path.basename(pdf_path)
# Open PDF and convert first page to image
doc = fitz.open(pdf_path)