MSivasandeep's picture
Update app.py
7b3fd1b verified
Raw History Blame Contribute Delete
22.3 kB
from flask import Flask, render_template, request, jsonify, session, redirect, url_for
from datetime import datetime, timedelta
import json
import os
import uuid
import qrcode
import io
import base64
import requests
app = Flask(__name__)
app.secret_key = os.environ.get('SECRET_KEY', 'dev-secret-key')
app.config['SESSION_TYPE'] = 'filesystem'
# EmailJS configuration - Direct credentials
EMAILJS_SERVICE_ID = 'service_fcct3nk'
EMAILJS_TEMPLATE_ID = 'template_ak5nnwt'
EMAILJS_PUBLIC_KEY = 'RjpihbHV1xKSW_PTv'
EMAILJS_PRIVATE_KEY = 'HimkIjnaVu1416pMUHzlZ'
# Enhanced museum data with proper pricing
MUSEUMS = {
"national_museum": {
"id": "national_museum",
"name": "National Museum, New Delhi",
"location": "New Delhi",
"description": "One of India's largest museums with over 200,000 artifacts spanning 5,000 years of Indian history.",
"base_price": 50,
"pricing": {
"indian": {
"adult": {"weekday": 50, "weekend": 75},
"child": {"weekday": 20, "weekend": 30},
"senior": {"weekday": 25, "weekend": 40}
},
"foreigner": {
"adult": {"weekday": 500, "weekend": 650},
"child": {"weekday": 200, "weekend": 300}
}
},
"extra_charges": {
"photography": 200,
"audio_guide": 100,
"guided_tour": 300
},
"image": "https://images.unsplash.com/photo-1591386768477-84ff7c578a13?w=400&h=300&fit=crop",
"languages": ["Hindi", "English", "Tamil", "Bengali"],
"timings": "10:00 AM - 6:00 PM",
"closed_on": "Monday",
"best_for": ["History", "Archaeology", "Art"],
"rating": 4.5,
"coordinates": {"lat": 28.6129, "lng": 77.2295},
"address": "Janpath Road, Rajpath Area, New Delhi, Delhi 110011",
"map_url": "https://maps.google.com/?q=National+Museum+New+Delhi"
},
"indian_museum": {
"id": "indian_museum",
"name": "Indian Museum, Kolkata",
"location": "Kolkata",
"description": "Established in 1814, it is the oldest and largest museum in India with rare collections of antiques.",
"base_price": 20,
"pricing": {
"indian": {
"adult": {"weekday": 20, "weekend": 30},
"child": {"weekday": 10, "weekend": 15},
"senior": {"weekday": 10, "weekend": 15}
},
"foreigner": {
"adult": {"weekday": 200, "weekend": 250},
"child": {"weekday": 100, "weekend": 150}
}
},
"extra_charges": {
"photography": 100,
"audio_guide": 50,
"guided_tour": 150
},
"image": "https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=400&h=300&fit=crop",
"languages": ["Hindi", "English", "Bengali"],
"timings": "10:00 AM - 5:00 PM",
"closed_on": "Monday",
"best_for": ["Ancient History", "Natural History", "Art"],
"rating": 4.3,
"coordinates": {"lat": 22.5583, "lng": 88.3508},
"address": "27, Jawaharlal Nehru Rd, Park Street, Kolkata, West Bengal 700016",
"map_url": "https://maps.google.com/?q=Indian+Museum+Kolkata"
},
"chhatrapati_museum": {
"id": "chhatrapati_museum",
"name": "Chhatrapati Shivaji Maharaj Vastu Sangrahalaya, Mumbai",
"location": "Mumbai",
"description": "Formerly Prince of Wales Museum, features Indo-Saracenic architecture and over 50,000 exhibits.",
"base_price": 100,
"pricing": {
"indian": {
"adult": {"weekday": 100, "weekend": 150},
"child": {"weekday": 50, "weekend": 75},
"senior": {"weekday": 50, "weekend": 75}
},
"foreigner": {
"adult": {"weekday": 700, "weekend": 900},
"child": {"weekday": 350, "weekend": 450}
}
},
"extra_charges": {
"photography": 300,
"audio_guide": 150,
"guided_tour": 500
},
"image": "https://images.unsplash.com/photo-1580503593984-6d6d4e8da530?w=400&h=300&fit=crop",
"languages": ["Hindi", "English", "Marathi"],
"timings": "10:15 AM - 6:00 PM",
"closed_on": "Monday",
"best_for": ["Architecture", "Sculptures", "Paintings"],
"rating": 4.7,
"coordinates": {"lat": 18.9260, "lng": 72.8320},
"address": "159-161, Mahatma Gandhi Road, Fort, Mumbai, Maharashtra 400023",
"map_url": "https://maps.google.com/?q=Chhatrapati+Shivaji+Maharaj+Vastu+Sangrahalaya+Mumbai"
},
"salar_jung": {
"id": "salar_jung",
"name": "Salar Jung Museum, Hyderabad",
"location": "Hyderabad",
"description": "Third largest museum in India featuring one-man collections of Nawab Mir Yousuf Ali Khan.",
"base_price": 20,
"pricing": {
"indian": {
"adult": {"weekday": 20, "weekend": 30},
"child": {"weekday": 10, "weekend": 15},
"senior": {"weekday": 10, "weekend": 15}
},
"foreigner": {
"adult": {"weekday": 200, "weekend": 250},
"child": {"weekday": 100, "weekend": 150}
}
},
"extra_charges": {
"photography": 150,
"audio_guide": 80,
"guided_tour": 200
},
"image": "https://images.unsplash.com/photo-1578662996442-48f60103fc96?w=400&h=300&fit=crop",
"languages": ["Hindi", "English", "Telugu", "Urdu"],
"timings": "10:00 AM - 5:00 PM",
"closed_on": "Friday",
"best_for": ["Personal Collections", "Artifacts", "Manuscripts"],
"rating": 4.4,
"coordinates": {"lat": 17.3716, "lng": 78.4805},
"address": "Salar Jung Road, Near Minar Function Hall, Hyderabad, Telangana 500002",
"map_url": "https://maps.google.com/?q=Salar+Jung+Museum+Hyderabad"
}
}
# Available time slots
TIME_SLOTS = [
"10:00 AM - 11:00 AM",
"11:00 AM - 12:00 PM",
"12:00 PM - 01:00 PM",
"02:00 PM - 03:00 PM",
"03:00 PM - 04:00 PM",
"04:00 PM - 05:00 PM"
]
# Chatbot responses
CHATBOT_RESPONSES = {
"welcome": {
"message": "πŸ‘‹ Hello! I'm your Museum Assistant. How can I help you today?",
"options": [
{"text": "🎫 Book Tickets", "value": "book_tickets"},
{"text": "πŸ›οΈ Best Museums", "value": "best_museums"},
{"text": "🌐 Language Support", "value": "languages"},
{"text": "πŸ’° Pricing Info", "value": "pricing"},
{"text": "⏰ Timings", "value": "timings"},
{"text": "πŸ“ Museum Locations", "value": "locations"},
{"text": "❓ General Help", "value": "help"}
]
},
"book_tickets": {
"message": "Great! Let me help you book tickets. Which museum would you like to visit?",
"options": [
{"text": "National Museum, Delhi", "value": "national_museum"},
{"text": "Indian Museum, Kolkata", "value": "indian_museum"},
{"text": "Chhatrapati Museum, Mumbai", "value": "chhatrapati_museum"},
{"text": "Salar Jung Museum, Hyderabad", "value": "salar_jung"},
{"text": "πŸ”™ Back to Main Menu", "value": "back"}
]
},
"best_museums": {
"message": "Here are our top-rated museums based on visitor reviews:",
"options": [
{"text": "πŸ₯‡ Chhatrapati Museum (4.7⭐)", "value": "chhatrapati_details"},
{"text": "πŸ₯ˆ National Museum (4.5⭐)", "value": "national_details"},
{"text": "πŸ₯‰ Indian Museum (4.3⭐)", "value": "indian_details"},
{"text": "Salar Jung Museum (4.4⭐)", "value": "salarjung_details"},
{"text": "πŸ”™ Back to Main Menu", "value": "back"}
]
},
"languages": {
"message": "We support multiple Indian languages for your convenience:",
"options": [
{"text": "Hindi", "value": "hindi_info"},
{"text": "English", "value": "english_info"},
{"text": "Regional Languages", "value": "regional_info"},
{"text": "πŸ”™ Back to Main Menu", "value": "back"}
]
},
"pricing": {
"message": "Affordable ticket prices for all museums:",
"options": [
{"text": "National Museum: β‚Ή50-650", "value": "national_price"},
{"text": "Indian Museum: β‚Ή20-250", "value": "indian_price"},
{"text": "Chhatrapati Museum: β‚Ή100-900", "value": "chhatrapati_price"},
{"text": "Salar Jung Museum: β‚Ή20-250", "value": "salarjung_price"},
{"text": "πŸ”™ Back to Main Menu", "value": "back"}
]
},
"timings": {
"message": "Most museums are open from 10:00 AM to 5:00 PM. Closed on Mondays.",
"options": [
{"text": "Specific Museum Timings", "value": "specific_timings"},
{"text": "Holiday Schedule", "value": "holidays"},
{"text": "πŸ”™ Back to Main Menu", "value": "back"}
]
},
"locations": {
"message": "Here are the museum locations across India:",
"options": [
{"text": "πŸ“ National Museum - Delhi", "value": "national_location"},
{"text": "πŸ“ Indian Museum - Kolkata", "value": "indian_location"},
{"text": "πŸ“ Chhatrapati Museum - Mumbai", "value": "chhatrapati_location"},
{"text": "πŸ“ Salar Jung Museum - Hyderabad", "value": "salarjung_location"},
{"text": "πŸ”™ Back to Main Menu", "value": "back"}
]
},
"help": {
"message": "I can help you with: ticket booking, museum information, pricing, timings, locations, and language support. What would you like to know?",
"options": [
{"text": "🎫 Book Tickets", "value": "book_tickets"},
{"text": "πŸ›οΈ Museum Info", "value": "best_museums"},
{"text": "πŸ“ Locations", "value": "locations"},
{"text": "πŸ”™ Back to Main Menu", "value": "back"}
]
}
}
# Store bookings
bookings = {}
def generate_qr_code(data):
"""Generate QR code as base64 string"""
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=2,
border=4,
)
qr.add_data(data)
qr.make(fit=True)
img = qr.make_image(fill_color="black", back_color="white")
buffer = io.BytesIO()
img.save(buffer, format="PNG")
buffer.seek(0)
img_str = base64.b64encode(buffer.getvalue()).decode()
return f"data:image/png;base64,{img_str}"
def calculate_total_amount(booking_data, museum):
"""Calculate total amount based on visitor types and extras"""
total = 0
# Get day type (weekday/weekend)
visit_date = datetime.strptime(booking_data['visit_date'], '%Y-%m-%d')
is_weekend = visit_date.weekday() >= 5 # 5=Saturday, 6=Sunday
day_type = 'weekend' if is_weekend else 'weekday'
# Calculate ticket prices
visitor_type = booking_data.get('visitor_type', 'indian')
# Adult tickets
adults = int(booking_data.get('adults', 0))
adult_price = museum['pricing'][visitor_type]['adult'][day_type]
total += adults * adult_price
# Child tickets
children = int(booking_data.get('children', 0))
child_price = museum['pricing'][visitor_type]['child'][day_type]
total += children * child_price
# Senior tickets (if applicable)
seniors = int(booking_data.get('seniors', 0))
if 'senior' in museum['pricing'][visitor_type]:
senior_price = museum['pricing'][visitor_type]['senior'][day_type]
total += seniors * senior_price
# Extra charges
if booking_data.get('photography') == 'yes':
total += museum['extra_charges']['photography']
if booking_data.get('audio_guide') == 'yes':
total += museum['extra_charges']['audio_guide']
if booking_data.get('guided_tour') == 'yes':
total += museum['extra_charges']['guided_tour']
return total
def send_booking_confirmation(booking_data):
"""Send booking confirmation email using EmailJS"""
try:
print("πŸ”§ EmailJS Configuration Check:")
print(f" Service ID: {EMAILJS_SERVICE_ID}")
print(f" Template ID: {EMAILJS_TEMPLATE_ID}")
print(f" Public Key: {EMAILJS_PUBLIC_KEY}")
print(f" Private Key: {EMAILJS_PRIVATE_KEY}")
# EmailJS API endpoint
url = "https://api.emailjs.com/api/v1.0/email/send"
# Prepare the email data
email_data = {
"service_id": EMAILJS_SERVICE_ID,
"template_id": EMAILJS_TEMPLATE_ID,
"user_id": EMAILJS_PUBLIC_KEY,
"accessToken": EMAILJS_PRIVATE_KEY,
"template_params": {
"customer_name": booking_data['customer_name'],
"customer_email": booking_data['customer_email'],
"museum_name": booking_data['museum_name'],
"booking_id": booking_data['booking_id'],
"visit_date": booking_data['visit_date'],
"time_slot": booking_data['time_slot'],
"adults": str(booking_data['adults']),
"children": str(booking_data['children']),
"seniors": str(booking_data['seniors']),
"visitor_type": booking_data['visitor_type'].title(),
"total_amount": f"β‚Ή{booking_data['total_amount']}",
"museum_address": booking_data['museum_address'],
"booking_date": booking_data['booking_date'],
"to_email": booking_data['customer_email']
}
}
print(f"πŸ“§ Sending email to: {booking_data['customer_email']}")
print(f"πŸ›οΈ Museum: {booking_data['museum_name']}")
print(f"🎫 Booking ID: {booking_data['booking_id']}")
# Send the request to EmailJS
response = requests.post(url, json=email_data, timeout=30)
print(f"πŸ“¨ EmailJS Response Status: {response.status_code}")
print(f"πŸ“¨ EmailJS Response Text: {response.text}")
if response.status_code == 200:
print(f"βœ… Email sent successfully to {booking_data['customer_email']}")
return True
else:
print(f"❌ EmailJS error: {response.status_code} - {response.text}")
return False
except Exception as e:
print(f"❌ Error sending email: {str(e)}")
return False
@app.route('/')
def home():
return render_template('index.html')
@app.route('/museums')
def museums():
return render_template('museums.html', museums=MUSEUMS)
@app.route('/museum/<museum_id>')
def museum_detail(museum_id):
museum = MUSEUMS.get(museum_id)
if not museum:
return redirect(url_for('museums'))
current_date = datetime.now().strftime('%Y-%m-%d')
return render_template('booking.html', museum=museum, time_slots=TIME_SLOTS, now=current_date)
@app.route('/api/calculate-price', methods=['POST'])
def calculate_price():
try:
data = request.get_json()
museum_id = data.get('museum_id')
visit_date = data.get('visit_date')
if not museum_id or not visit_date:
return jsonify({'success': False, 'error': 'Missing required fields'})
museum = MUSEUMS.get(museum_id)
if not museum:
return jsonify({'success': False, 'error': 'Invalid museum'})
# Calculate prices for different categories
visit_date_obj = datetime.strptime(visit_date, '%Y-%m-%d')
is_weekend = visit_date_obj.weekday() >= 5
day_type = 'weekend' if is_weekend else 'weekday'
prices = {
'indian_adult': museum['pricing']['indian']['adult'][day_type],
'indian_child': museum['pricing']['indian']['child'][day_type],
'foreigner_adult': museum['pricing']['foreigner']['adult'][day_type],
'foreigner_child': museum['pricing']['foreigner']['child'][day_type],
'photography': museum['extra_charges']['photography'],
'audio_guide': museum['extra_charges']['audio_guide'],
'guided_tour': museum['extra_charges']['guided_tour'],
'is_weekend': is_weekend,
'day_type': day_type
}
# Add senior pricing if available
if 'senior' in museum['pricing']['indian']:
prices['indian_senior'] = museum['pricing']['indian']['senior'][day_type]
return jsonify({'success': True, 'prices': prices})
except Exception as e:
return jsonify({'success': False, 'error': str(e)})
@app.route('/api/book', methods=['POST'])
def book_ticket():
try:
data = request.get_json()
required_fields = ['museum_id', 'visit_date', 'time_slot', 'name', 'email', 'phone']
for field in required_fields:
if field not in data or not data[field]:
return jsonify({'success': False, 'error': f'Missing field: {field}'})
museum_id = data['museum_id']
if museum_id not in MUSEUMS:
return jsonify({'success': False, 'error': 'Invalid museum'})
museum = MUSEUMS[museum_id]
# Calculate total amount
total_amount = calculate_total_amount(data, museum)
# Generate booking ID
booking_id = str(uuid.uuid4())[:8].upper()
# Generate QR code data
qr_data = f"""
Museum Ticket - {museum['name']}
Booking ID: {booking_id}
Date: {data['visit_date']} | Time: {data['time_slot']}
Adults: {data.get('adults', 0)} | Children: {data.get('children', 0)}
Total: β‚Ή{total_amount}
Name: {data['name']}
""".strip()
qr_code = generate_qr_code(qr_data)
# Create booking record
booking = {
'booking_id': booking_id,
'museum_id': museum_id,
'museum_name': museum['name'],
'visit_date': data['visit_date'],
'time_slot': data['time_slot'],
'visitor_type': data.get('visitor_type', 'indian'),
'adults': int(data.get('adults', 0)),
'children': int(data.get('children', 0)),
'seniors': int(data.get('seniors', 0)),
'photography': data.get('photography', 'no'),
'audio_guide': data.get('audio_guide', 'no'),
'guided_tour': data.get('guided_tour', 'no'),
'total_amount': total_amount,
'customer_name': data['name'],
'customer_email': data['email'],
'customer_phone': data['phone'],
'language': data.get('language', 'English'),
'booking_date': datetime.now().strftime('%Y-%m-%d %H:%M:%S'),
'status': 'confirmed',
'qr_code': qr_code,
'museum_address': museum.get('address', ''),
'map_url': museum.get('map_url', '')
}
bookings[booking_id] = booking
# Send confirmation email using EmailJS
print(f"πŸš€ Starting email sending process for booking {booking_id}")
email_sent = send_booking_confirmation(booking)
return jsonify({
'success': True,
'booking_id': booking_id,
'booking': booking,
'email_sent': email_sent
})
except Exception as e:
print(f"❌ Booking error: {str(e)}")
return jsonify({'success': False, 'error': str(e)})
@app.route('/booking/<booking_id>')
def booking_confirmation(booking_id):
booking = bookings.get(booking_id)
if not booking:
return redirect(url_for('home'))
return render_template('confirmation.html', booking=booking)
@app.route('/api/chatbot/start', methods=['POST'])
def chatbot_start():
return jsonify(CHATBOT_RESPONSES['welcome'])
@app.route('/api/chatbot/response', methods=['POST'])
def chatbot_response():
data = request.get_json()
user_input = data.get('input')
if user_input in CHATBOT_RESPONSES:
response = CHATBOT_RESPONSES[user_input]
if user_input.endswith('_details'):
museum_id = user_input.replace('_details', '_museum')
if museum_id in MUSEUMS:
museum = MUSEUMS[museum_id]
response = {
"message": f"πŸ›οΈ {museum['name']}\n⭐ Rating: {museum['rating']}/5\nπŸ“ Location: {museum['location']}\nπŸ’° Price: β‚Ή{museum['base_price']} onwards\n⏰ Timings: {museum['timings']}\n🚫 Closed: {museum['closed_on']}\n\n{museum['description']}",
"options": [
{"text": "🎫 Book Tickets", "value": museum_id},
{"text": "πŸ“ View Location", "value": f"{museum_id}_location"},
{"text": "πŸ”™ Back to Museums", "value": "best_museums"},
{"text": "πŸ”™ Main Menu", "value": "back"}
]
}
elif user_input.endswith('_location'):
museum_id = user_input.replace('_location', '_museum')
if museum_id in MUSEUMS:
museum = MUSEUMS[museum_id]
response = {
"message": f"πŸ“ {museum['name']}\n🏠 {museum['address']}\n\nπŸ—ΊοΈ Map: {museum['map_url']}",
"options": [
{"text": "🎫 Book Tickets", "value": museum_id},
{"text": "πŸ”™ Back to Locations", "value": "locations"},
{"text": "πŸ”™ Main Menu", "value": "back"}
]
}
return jsonify(response)
else:
return jsonify({
"message": "I'm not sure I understand. Please select from the options below:",
"options": CHATBOT_RESPONSES['welcome']['options']
})
if __name__ == '__main__':
app.run(debug=False, host='0.0.0.0', port=7860)