Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456781 unmodified line10111213141517 unmodified lines333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261274 unmodified lines1321331341351361371381391401411421431441451461471481491501511521531541551561571581597 unmodified lines16716816917017117217314 unmodified lines18818919019119219311 unmodified lines2052062072082092102114 unmodified lines2162172182192202217 unmodified lines2292302312322332342352 unmodified lines2382392402412422432444 unmodified lines249250251import osimport timeimport requestsimport reimport gradio as grfrom reportlab.pdfgen import canvasfrom reportlab.lib.pagesizes import letterimport tempfile1 unmodified line# Load API key securely from environmentGROQ_API_KEY = os.getenv("GROQ_API_KEY")MOODS = ["Adventure",17 unmodified lines"Any": "images/default.png"}def create_leaflet_map(locations):markers_js = ""for loc in locations:markers_js += f"""L.marker([{loc['lat']}, {loc['lng']}]).addTo(map).bindPopup("<b>{loc['name']}</b>");"""center_lat = locations[0]['lat'] if locations else 20center_lng = locations[0]['lng'] if locations else 0html = f"""<div id="map" style="width: 100%; height: 400px; margin-top: 20px;"></div><linkrel="stylesheet"href="https://unpkg.com/leaflet@1.9.3/dist/leaflet.css"crossorigin=""/><scriptsrc="https://unpkg.com/leaflet@1.9.3/dist/leaflet.js"crossorigin=""></script><script>var map = L.map('map').setView([{center_lat}, {center_lng}], 6);L.tileLayer('https://{{s}}.tile.openstreetmap.org/{{z}}/{{x}}/{{y}}.png', {{attribution: '© OpenStreetMap contributors',}}).addTo(map);{markers_js}</script>"""return htmldef geocode_location(place_name):url = "https://nominatim.openstreetmap.org/search"params = {"q": place_name, "format": "json", "limit": 1}headers = {"User-Agent": "FeelAwayApp/1.0 (mathushawlika1221@gmail.com)"}try:response = requests.get(url, params=params, headers=headers, timeout=5)if response.status_code == 200:data = response.json()if data:lat = float(data[0]["lat"])lon = float(data[0]["lon"])return lat, lonexcept Exception:passreturn None, Nonedef extract_places(itinerary_text):# Simple heuristic: extract capitalized phrases (names)pattern = r"\b([A-Z][a-z]+(?:\s[A-Z][a-z]+)*)\b"matches = re.findall(pattern, itinerary_text)blacklist = {"The", "And", "For", "With", "From", "Your", "Day", "Enjoy", "Start", "Begin"}places = []for match in matches:if match not in blacklist and len(match) > 2:places.append(match)# Remove duplicates preserving orderseen = set()unique_places = []for p in places:if p not in seen:seen.add(p)unique_places.append(p)return unique_placesdef call_groq_model(prompt):if not GROQ_API_KEY:return "**Error:** Missing GROQ_API_KEY in environment settings."url = "https://api.groq.com/openai/v1/chat/completions"headers = {"Authorization": f"Bearer {GROQ_API_KEY}", "Content-Type": "application/json"}payload = {"model": "gemma2-9b-it","messages": [{"role": "system", "content": "You are an expert travel planner."},{"role": "user", "content": prompt}],"temperature": 1,"max_tokens": 1024}try:response = requests.post(url, headers=headers, json=payload, timeout=30)response.raise_for_status()data = response.json()return data["choices"][0]["message"]["content"]except Exception as e:return f"**Error calling model:** {e}"def generate_itinerary(mood, location, budget, days):mood_text = "any mood" if mood == "Any" else moodbudget_text = "any budget" if budget == "Any" else budget4 unmodified linesf"The mood of the traveler is {mood_text} and the budget is {budget_text}. "f"Use Markdown formatting with **bold headings** for days and time slots.")itinerary_text = call_groq_model(prompt)image_path = MOOD_IMAGES.get(mood, MOOD_IMAGES["Any"])# If API failed, don't proceed to mapif itinerary_text.startswith("**Error"):return itinerary_text, None, gr.update(visible=False), "", gr.update(visible=False)# Extract place namesplaces = extract_places(itinerary_text)locations = []for place in places:lat, lng = geocode_location(place)if lat and lng:locations.append({"name": place, "lat": lat, "lng": lng})time.sleep(1)if not locations:locations = [{"name": "World", "lat": 20, "lng": 0}]map_html = create_leaflet_map(locations)return itinerary_text, image_path, gr.update(visible=True), map_html, gr.update(visible=True)def generate_pdf(itinerary_text):if not itinerary_text.strip():7 unmodified linesline_height = 12font_size = 10c.setFont("Courier", font_size)max_chars_per_line = int((width - 2 * margin) / (font_size * 0.6))x = marginy = height - margin14 unmodified linesreturn temp_pdf.namewith gr.Blocks(theme=gr.themes.Default(primary_hue="teal", secondary_hue="teal")) as demo:header_html = """<style>@keyframes colorCycle {11 unmodified linescolor: #007777;font-size: 18px;margin-top: 4px;font-weight:bold;}</style><div style='text-align: center;'>4 unmodified lineswith gr.Row():gr.HTML(header_html)with gr.Row():mood = gr.Dropdown(MOODS, label="Mood", value="Any", info="Select the mood of your trip")location = gr.Textbox(label="Destination", placeholder="e.g., India, Japan, France (leave blank for Any)", info="Where do you want to go?")7 unmodified lineswith gr.Column():itinerary_output = gr.Markdown(label="Generated Itinerary")image_output = gr.Image(label="Travel Mood Image", type="filepath", visible=False)map_output = gr.HTML(visible=False)with gr.Column():download_btn = gr.Button("📥 Download Itinerary as PDF", variant="secondary")2 unmodified linesgenerate_btn.click(generate_itinerary,inputs=[mood, location, budget, days],outputs=[itinerary_output, image_output, image_output, map_output, map_output])download_btn.click(4 unmodified linesdemo.launch()1234561 unmodified line89101112131417 unmodified lines3233343536374 unmodified lines424344454647484950515253545556575859606162637 unmodified lines71727374757677787914 unmodified lines94959697989910011 unmodified lines1121131141151161174 unmodified lines1221231241251261271287 unmodified lines1361371381391401412 unmodified lines1441451461471481491504 unmodified lines155156157158import osimport gradio as grfrom groq import Groqfrom reportlab.pdfgen import canvasfrom reportlab.lib.pagesizes import letterimport tempfile1 unmodified line# Load API key securely from environmentGROQ_API_KEY = os.getenv("GROQ_API_KEY")client = Groq(api_key=GROQ_API_KEY)MOODS = ["Adventure",17 unmodified lines"Any": "images/default.png"}def generate_itinerary(mood, location, budget, days):mood_text = "any mood" if mood == "Any" else moodbudget_text = "any budget" if budget == "Any" else budget4 unmodified linesf"The mood of the traveler is {mood_text} and the budget is {budget_text}. "f"Use Markdown formatting with **bold headings** for days and time slots.")completion = client.chat.completions.create(model="gemma2-9b-it",messages=[{"role": "system", "content": "You are an expert travel planner."},{"role": "user", "content": prompt}],temperature=1,max_completion_tokens=1024,top_p=1,stream=False)itinerary_text = completion.choices[0].message.contentimage_path = MOOD_IMAGES.get(mood, MOOD_IMAGES["Any"])return itinerary_text, image_path, gr.update(visible=True)def generate_pdf(itinerary_text):if not itinerary_text.strip():7 unmodified linesline_height = 12font_size = 10c.setFont("Courier", font_size)max_chars_per_line = int((width - 2 * margin) / (font_size * 0.6))x = marginy = height - margin14 unmodified linesreturn temp_pdf.namewith gr.Blocks(theme=gr.themes.Default(primary_hue="teal", secondary_hue="teal")) as demo:# Header with gr.HTML for styles and animationheader_html = """<style>@keyframes colorCycle {11 unmodified linescolor: #007777;font-size: 18px;margin-top: 4px;}</style><div style='text-align: center;'>4 unmodified lineswith gr.Row():gr.HTML(header_html)# Inputswith gr.Row():mood = gr.Dropdown(MOODS, label="Mood", value="Any", info="Select the mood of your trip")location = gr.Textbox(label="Destination", placeholder="e.g., India, Japan, France (leave blank for Any)", info="Where do you want to go?")7 unmodified lineswith gr.Column():itinerary_output = gr.Markdown(label="Generated Itinerary")image_output = gr.Image(label="Travel Mood Image", type="filepath", visible=False)with gr.Column():download_btn = gr.Button("📥 Download Itinerary as PDF", variant="secondary")2 unmodified linesgenerate_btn.click(generate_itinerary,inputs=[mood, location, budget, days],outputs=[itinerary_output, image_output, image_output])download_btn.click(4 unmodified linesdemo.launch()
app.py+23-116