TSM / t_s_m.py
Shahg431's picture
Upload t_s_m.py
7d9c57d verified
# -*- coding: utf-8 -*-
"""T S M.ipynb
Automatically generated by Colab.
Original file is located at
https://colab.research.google.com/drive/1aa7j80PEKtklLchunk-SKWhzhwCj-PMr
"""
# ==============================
# INSTALL DEPENDENCIES
# ==============================
!pip install -q openai gradio pandas
# ==============================
# IMPORT LIBRARIES
# ==============================
from openai import OpenAI
import os
import gradio as gr
import pandas as pd
from datetime import datetime
# ==============================
# ADD YOUR GROQ API KEY HERE
# ==============================
os.environ["GROQ_API_KEY"] = "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"
# ==============================
# SETUP GROQ CLIENT
# ==============================
client = OpenAI(
api_key=os.environ.get("GROQ_API_KEY"),
base_url="https://api.groq.com/openai/v1",
)
# ==============================
# GLOBAL STORAGE
# ==============================
users = {} # {username: password}
bookings = [] # list of booking dicts
notifications = [] # list of messages to users
ADMIN_CREDENTIALS = {"admin": "admin123"} # default admin
# ==============================
# SYSTEM PROMPT (AI TRAVEL ASSISTANT)
# ==============================
system_prompt = """
You are TravelGenZ AI, a smart travel assistant.
You give:
1. Distance between departure and destination
2. Airplane vs Bus comparison (time, cost, comfort)
3. Popular attractions & best hotels
4. Estimated cost & travel tips
5. Friendly, GenZ tone with emojis
6. Keep structured output
"""
# ==============================
# USER FUNCTIONS
# ==============================
def register_user(name, password):
if name in users:
return "❌ User already exists"
users[name] = password
return f"βœ… Registered successfully! Welcome, {name}"
def login_user(name, password):
if name not in users:
return "❌ User not found. Please register."
if users[name] != password:
return "❌ Wrong password."
return f"βœ… Logged in successfully! Welcome back, {name}"
# Travel Chat AI
def travel_chat_ai(departure, destination, travelers, mode, date, name):
prompt = f"{system_prompt}\nUser is {name}. Traveling from {departure} to {destination} on {date} for {travelers} people by {mode}. Provide distance, travel comparison, popular places and hotels, estimated cost."
response = client.responses.create(
model="openai/gpt-oss-20b",
input=prompt
)
return response.output_text
# Make booking
def make_booking(name, departure, destination, travelers, mode, date, mobile):
booking_id = len(bookings)+1
booking = {
"Booking ID": booking_id,
"Name": name,
"Mobile": mobile,
"Departure": departure,
"Destination": destination,
"Travelers": travelers,
"Mode": mode,
"Date": date,
"Status": "Pending"
}
bookings.append(booking)
return f"βœ… Booking submitted! Your Booking ID is {booking_id}. Admin will review soon."
# Admin functions
def admin_login(name, password):
if name not in ADMIN_CREDENTIALS or ADMIN_CREDENTIALS[name] != password:
return "❌ Wrong Admin credentials"
return "βœ… Admin login successful"
def view_bookings(admin_name, admin_password):
if admin_name not in ADMIN_CREDENTIALS or ADMIN_CREDENTIALS[admin_name] != admin_password:
return "❌ Wrong Admin credentials"
if not bookings:
return "No bookings yet."
return pd.DataFrame(bookings)
def process_booking(admin_name, admin_password, booking_id, action):
if admin_name not in ADMIN_CREDENTIALS or ADMIN_CREDENTIALS[admin_name] != admin_password:
return "❌ Wrong Admin credentials"
global bookings
for b in bookings:
if b["Booking ID"] == int(booking_id):
if action == "Accept":
b["Status"] = "Accepted"
notifications.append(f"βœ… Your booking {booking_id} has been accepted by admin!")
return f"Booking {booking_id} accepted"
elif action == "Reject":
b["Status"] = "Rejected"
notifications.append(f"❌ Your booking {booking_id} has been rejected by admin.")
return f"Booking {booking_id} rejected"
return "Booking ID not found"
def get_notifications():
return "\n".join(notifications) if notifications else "No new messages"
# ==============================
# GRADIO UI
# ==============================
with gr.Blocks(theme=gr.themes.Soft(), title="TravelGenZ AI") as app:
gr.Markdown("# 🌍✈ TravelGenZ AI Booking System")
gr.Markdown("### Professional travel booking with AI guidance, hotels & attractions πŸŽ’")
with gr.Tab("πŸ“ User Login/Register"):
with gr.Row():
reg_name = gr.Textbox(label="Name")
reg_pass = gr.Textbox(label="Password", type="password")
reg_btn = gr.Button("Register")
reg_out = gr.Textbox()
reg_btn.click(register_user, [reg_name, reg_pass], reg_out)
with gr.Row():
login_name = gr.Textbox(label="Name")
login_pass = gr.Textbox(label="Password", type="password")
login_btn = gr.Button("Login")
login_out = gr.Textbox()
login_btn.click(login_user, [login_name, login_pass], login_out)
with gr.Tab("πŸ’¬ Travel Assistant"):
dep_city = gr.Textbox(label="Departure City")
dest_city = gr.Textbox(label="Destination City")
travelers = gr.Number(label="Number of Travelers")
travel_mode = gr.Radio(["Airplane", "Bus"], label="Travel Mode")
travel_date = gr.Textbox(label="Travel Date (YYYY-MM-DD)")
user_name = gr.Textbox(label="Your Name")
mobile = gr.Textbox(label="Mobile Number")
chat_btn = gr.Button("Get AI Travel Info & Book")
chat_out = gr.Textbox()
chat_btn.click(
lambda d, dst, t, m, date, n, mob: travel_chat_ai(d, dst, t, m, date, n) + "\n\n" + make_booking(n, d, dst, t, m, date, mob),
[dep_city, dest_city, travelers, travel_mode, travel_date, user_name, mobile],
chat_out
)
with gr.Tab("πŸ“¨ User Notifications"):
notif_btn = gr.Button("Check Notifications")
notif_out = gr.Textbox()
notif_btn.click(get_notifications, [], notif_out)
with gr.Tab("πŸ‘¨β€πŸ’Ό Admin Panel"):
admin_name = gr.Textbox(label="Admin Name")
admin_pass = gr.Textbox(label="Password", type="password")
admin_login_btn = gr.Button("Login")
admin_login_out = gr.Textbox()
admin_login_btn.click(admin_login, [admin_name, admin_pass], admin_login_out)
view_btn = gr.Button("View Bookings")
bookings_out = gr.Dataframe()
view_btn.click(view_bookings, [admin_name, admin_pass], bookings_out)
booking_id = gr.Number(label="Booking ID")
action = gr.Radio(["Accept", "Reject"], label="Action")
process_btn = gr.Button("Process Booking")
process_out = gr.Textbox()
process_btn.click(process_booking, [admin_name, admin_pass, booking_id, action], process_out)
app.launch(share=True)
# ==============================
# INSTALL DEPENDENCIES
# ==============================
!pip install -q openai gradio pandas
# ==============================
# IMPORT LIBRARIES
# ==============================
from openai import OpenAI
import os
import gradio as gr
import pandas as pd
from datetime import datetime
# ==============================
# SET YOUR GROQ KEY HERE
# ==============================
os.environ["GROQ_API_KEY"] = "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"
# ==============================
# GROQ CLIENT
# ==============================
client = OpenAI(
api_key=os.environ.get("GROQ_API_KEY"),
base_url="https://api.groq.com/openai/v1",
)
# ==============================
# GLOBAL STORAGE
# ==============================
users = {} # username -> password
bookings = [] # all bookings
notifications = {} # username -> messages
ADMIN_USERNAME = "admin"
ADMIN_PASSWORD = "admin123"
# ==============================
# HELPER FUNCTIONS
# ==============================
def ai_travel_guide(departure, destination, travelers, mode):
"""Get AI-guided info about destination, hotels, attractions, distance & estimated cost"""
prompt = f"""
You are a professional travel guide.
A user wants to travel from {departure} to {destination}.
Travelers: {travelers}, Mode: {mode}.
Provide:
1. Distance in km
2. Estimated travel time
3. Estimated cost (simulate realistic)
4. Best hotels (top 3)
5. Popular attractions & museums
Format it with sections and emojis.
"""
response = client.responses.create(
model="openai/gpt-oss-20b",
input=prompt
)
return response.output_text
def register_user(username, password):
if username in users:
return "❌ Username already exists."
users[username] = password
notifications[username] = []
return "βœ… Registration successful! Please login."
def login_user(username, password):
if username not in users:
return None, "❌ User not found. Please register."
if users[username] != password:
return None, "❌ Incorrect password."
return username, f"βœ… Welcome {username}! Ready to plan your travel journey ✈️🌍"
def make_booking(username, departure, destination, travelers, mode, mobile):
booking_id = len(bookings) + 1
time_now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
booking = {
"Booking ID": booking_id,
"Username": username,
"Departure": departure,
"Destination": destination,
"Travelers": travelers,
"Mode": mode,
"Mobile": mobile,
"Status": "Pending",
"Time": time_now
}
bookings.append(booking)
return f"βœ… Booking submitted! Your booking ID is {booking_id}. Admin will review it shortly."
def admin_login(username, password):
if username != ADMIN_USERNAME or password != ADMIN_PASSWORD:
return None, "❌ Incorrect admin credentials."
return True, f"βœ… Welcome Admin {username}!"
def admin_accept_reject(booking_id, action):
global bookings
for b in bookings:
if b["Booking ID"] == int(booking_id):
if action == "Accept":
b["Status"] = "Accepted"
# Notify user
msg = f"""
πŸŽ‰βœ¨ Your Booking is Confirmed! βœ¨πŸŽ‰
Hello {b['Username']}! πŸ‘‹
Great news! Your travel plans with T S M from {b['Departure']} to {b['Destination']} are now confirmed! πŸ›«πŸ¨πŸŒ
Travelers: {b['Travelers']}, Mode: {b['Mode']}
Your flight & hotel details are all set πŸ“βœˆοΈπŸ¨
Safe travels & happy adventures! πŸš€πŸ’–πŸ§³
"""
notifications[b["Username"]].append(msg)
return f"βœ… Booking {booking_id} accepted & notification sent!"
else:
b["Status"] = "Rejected"
notifications[b["Username"]].append(f"❌ Booking {booking_id} has been rejected by admin.")
return f"βœ… Booking {booking_id} rejected."
return f"❌ Booking ID {booking_id} not found."
# ==============================
# GRADIO UI
# ==============================
with gr.Blocks(theme=gr.themes.Soft(), title="TSM Travel Agency") as app:
gr.Markdown("# 🌟 TSM Travel Agency AI 🌟")
gr.Markdown("Welcome to TSM Travel Agency! Plan your journey, explore destinations & book hassle-free ✈️🏨🌍")
with gr.Tab("πŸ“ User Portal"):
# Registration/Login
reg_username = gr.Textbox(label="Username")
reg_password = gr.Textbox(label="Password", type="password")
reg_btn = gr.Button("Register")
login_btn = gr.Button("Login")
login_msg = gr.Textbox()
current_user = gr.State()
reg_btn.click(register_user, [reg_username, reg_password], login_msg)
login_btn.click(login_user, [reg_username, reg_password], [current_user, login_msg])
# Travel Planning (after login)
dep_city = gr.Textbox(label="Departure City")
dest_city = gr.Textbox(label="Destination City")
travelers = gr.Number(label="Number of Travelers")
travel_mode = gr.Radio(["Airplane", "Bus"], label="Travel Mode")
mobile = gr.Textbox(label="Mobile Number")
guide_btn = gr.Button("Get Travel Guide & Book")
guide_output = gr.Textbox()
booking_output = gr.Textbox()
def guide_and_book(dep, dest, trav, mode, username, mobile):
if not username:
return "❌ Please login first.", ""
guide_info = ai_travel_guide(dep, dest, trav, mode)
book_msg = make_booking(username, dep, dest, trav, mode, mobile)
return guide_info, book_msg
guide_btn.click(guide_and_book, [dep_city, dest_city, travelers, travel_mode, current_user, mobile], [guide_output, booking_output])
with gr.Tab("πŸ‘¨β€πŸ’Ό Admin Panel"):
admin_user = gr.Textbox(label="Admin Username")
admin_pass = gr.Textbox(label="Admin Password", type="password")
admin_login_btn = gr.Button("Login as Admin")
admin_login_msg = gr.Textbox()
admin_state = gr.State()
view_bookings_btn = gr.Button("View All Bookings")
admin_bookings_output = gr.Dataframe()
booking_id_input = gr.Number(label="Booking ID")
accept_btn = gr.Button("Accept Booking")
reject_btn = gr.Button("Reject Booking")
admin_action_output = gr.Textbox()
admin_login_btn.click(admin_login, [admin_user, admin_pass], [admin_state, admin_login_msg])
view_bookings_btn.click(lambda: pd.DataFrame(bookings), [], admin_bookings_output)
accept_btn.click(admin_accept_reject, [booking_id_input, gr.State("Accept")], admin_action_output)
reject_btn.click(admin_accept_reject, [booking_id_input, gr.State("Reject")], admin_action_output)
with gr.Tab("πŸ“¬ Notifications"):
notif_user = gr.Textbox(label="Enter your username to see notifications")
notif_output = gr.Textbox()
def show_notifications(u):
msgs = notifications.get(u, [])
if not msgs:
return "No notifications yet."
return "\n\n".join(msgs)
gr.Button("Show Notifications").click(show_notifications, notif_user, notif_output)
app.launch(share=True)