import os import gradio as gr from openai import OpenAI from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle from reportlab.lib.pagesizes import letter from reportlab.lib import colors # Load OpenAI key from Hugging Face Secrets api_key = os.environ.get("OPENAI_API_KEY") if not api_key: raise ValueError("Please add OPENAI_API_KEY in your Space settings.") client = OpenAI(api_key=api_key) # ---------- PDF CREATION ---------- def create_pdf(text, filename="SmartTravelAI_Itinerary.pdf"): styles = getSampleStyleSheet() heading_style = ParagraphStyle( 'HeadingStyle', parent=styles['Heading2'], fontSize=16, textColor=colors.HexColor("#003366"), leading=18, spaceBefore=10, spaceAfter=6 ) normal_style = styles['BodyText'] doc = SimpleDocTemplate(filename, pagesize=letter) story = [] for line in text.split("\n"): line = line.strip() if not line: story.append(Spacer(1, 8)) continue # Detect headings like **Overview** if line.startswith("**") and line.endswith("**") and len(line) > 4: heading = line.replace("**", "") story.append(Paragraph(f"{heading}", heading_style)) else: cleaned = line.replace("**", "") story.append(Paragraph(cleaned, normal_style)) doc.build(story) return filename # ---------- AI ITINERARY GENERATION ---------- def generate_itinerary(destination, days, budget): system_msg = ( "You are SmartTravelAI, a professional travel planner. " "Return formatted text with bold headings and bullet points." ) user_msg = f""" Create a formatted travel itinerary. Destination: {destination} Days: {days} Budget: ${budget} USD Requirements: - Start with a bold trip title - Use headings: **Overview**, **Suggested Cities**, **Daily Plan**, **Budget Tips** - Use bullet points - Practical, fun, and concise """ response = client.chat.completions.create( model="gpt-4o-mini", messages=[ {"role": "system", "content": system_msg}, {"role": "user", "content": user_msg} ] ) itinerary_text = response.choices[0].message.content itinerary_text += "\n\n🔗 **Interactive App:** https://huggingface.co/spaces/naaijaz/SmartTravelAI" # Create PDF file pdf_path = create_pdf(itinerary_text) return itinerary_text, pdf_path # ---------- GRADIO INTERFACE ---------- demo = gr.Interface( fn=generate_itinerary, inputs=[ gr.Textbox(label="Destination Country / Region", placeholder="Italy, Japan, Jamaica…"), gr.Number(label="Number of Days", value=5), gr.Number(label="Budget (USD)", value=2000), ], outputs=[ gr.Markdown(label="Itinerary Preview"), gr.File(label="Download PDF") ], title="SmartTravelAI — AI Travel Planner (PDF Enabled)", description="Enter details to generate a custom itinerary and download it as a PDF.", ) demo.launch()