import gradio as gr import torch from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline MODEL_REPO = "Chuxia-sys/tinyllama-travelplanner-v2" print("πŸ”„ Loading model...") tokenizer = AutoTokenizer.from_pretrained(MODEL_REPO) model = AutoModelForCausalLM.from_pretrained( MODEL_REPO, torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32, device_map="auto" ) print("βœ… Model loaded successfully!") SYSTEM_PROMPT = """You are TinyLlama, a Philippine Travel Planner AI. You specialize in creating travel itineraries around the Philippines. Always give clear, day-by-day plans with real locations, food, and estimated costs. Never greet, never mention 'login' or 'listing'. Always reply in itinerary format.""" # --- CHAT FUNCTION USING MODEL'S TEMPLATE --- def chat_with_ai(message, history): # Build conversation in chat format messages = [{"role": "system", "content": SYSTEM_PROMPT}] for user, bot in history: messages.append({"role": "user", "content": user}) messages.append({"role": "assistant", "content": bot}) messages.append({"role": "user", "content": message}) # Apply chat template (respects model fine-tuning format) formatted_input = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) # Generate inputs = tokenizer(formatted_input, return_tensors="pt").to(model.device) outputs = model.generate( **inputs, max_new_tokens=400, temperature=0.3, top_p=0.9, repetition_penalty=1.15, do_sample=False, pad_token_id=tokenizer.eos_token_id ) response = tokenizer.decode(outputs[0], skip_special_tokens=True) reply = response.split(message)[-1].strip() # cleanup common leftover text reply = reply.replace("TinyLlama:", "").replace("User:", "").strip() return reply # --- STRUCTURED SINGLE QUERY --- def generate_itinerary(destination, start_date, end_date, num_people, budget, travel_type): query = ( f"Create a detailed itinerary for:\n" f"Destination: {destination}\nStart: {start_date}\nEnd: {end_date}\n" f"Travelers: {num_people}\nBudget: {budget}\nType: {travel_type}\n" "Output a clear, day-by-day travel plan." ) messages = [ {"role": "system", "content": SYSTEM_PROMPT}, {"role": "user", "content": query} ] formatted_input = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True) inputs = tokenizer(formatted_input, return_tensors="pt").to(model.device) outputs = model.generate( **inputs, max_new_tokens=400, temperature=0.3, top_p=0.9, repetition_penalty=1.1, do_sample=False, pad_token_id=tokenizer.eos_token_id ) response = tokenizer.decode(outputs[0], skip_special_tokens=True) reply = response.split(query)[-1].strip() return reply # --- BUILD UI --- with gr.Blocks(theme=gr.themes.Soft()) as demo: gr.Markdown("## 🧳 TinyLlama Travel Planner πŸ‡΅πŸ‡­\nRealistic, structured itineraries powered by TinyLlama.") with gr.Tab("πŸ’¬ Chat Mode"): chatbot = gr.Chatbot(height=450) msg = gr.Textbox(placeholder="Ask for an itinerary, e.g., '2-day relaxing trip near Manila under β‚±10000'") clear = gr.ClearButton([msg, chatbot]) def respond(message, history): reply = chat_with_ai(message, history) history.append((message, reply)) return "", history msg.submit(respond, [msg, chatbot], [msg, chatbot]) with gr.Tab("πŸ“‹ Structured Mode"): with gr.Row(): destination = gr.Textbox(label="Destination", placeholder="e.g., Baguio City, Benguet") travel_type = gr.Textbox(label="Travel Type", placeholder="e.g., Relaxation, Nature, Adventure") with gr.Row(): start_date = gr.Textbox(label="Start Date", placeholder="e.g., Oct 10, 2025") end_date = gr.Textbox(label="End Date", placeholder="e.g., Oct 12, 2025") with gr.Row(): num_people = gr.Number(label="Number of Travelers", value=2) budget = gr.Textbox(label="Budget", placeholder="e.g., β‚±15000") output = gr.Textbox(label="Generated Itinerary", lines=15) gen_btn = gr.Button("πŸ—ΊοΈ Generate Itinerary") gen_btn.click( generate_itinerary, [destination, start_date, end_date, num_people, budget, travel_type], output ) demo.launch(server_name="0.0.0.0", server_port=7860)