Rehman1603 commited on
Commit
39d8d5a
·
verified ·
1 Parent(s): a327d4c

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +58 -156
app.py CHANGED
@@ -1,169 +1,71 @@
1
- import gradio as gr
2
- from transformers import GPT2Tokenizer, GPT2LMHeadModel
3
  import torch
 
 
4
 
5
- # Step 1: Load the model and tokenizer from Hugging Face
6
- repo_id = "Rehman1603/fine_tune_gpt2_airline" # Replace with your Hugging Face repo ID
7
- model = GPT2LMHeadModel.from_pretrained(repo_id)
8
- tokenizer = GPT2Tokenizer.from_pretrained(repo_id)
9
 
10
- # Step 2: Set the model to evaluation mode
11
- model.eval()
 
12
 
13
- # Step 3: Define the dataset for filtering
14
- qa_data = [
15
- ("What is AstroSynth?", "AstroSynth is an innovative program designed to synthesize oils from celestial materials."),
16
- ("How does an airline manage its flight schedules?", "Airlines manage their flight schedules by using sophisticated software that takes into account factors such as demand, aircraft availability, airport slots, and regulatory requirements. The process involves planning, scheduling, and optimizing routes to maximize efficiency and profitability."),
17
- ("What is the role of a load controller in an airline?", "A load controller ensures that the weight and balance of an aircraft are within safe limits. They coordinate with various departments to determine the optimal distribution of cargo, baggage, and passengers to ensure a safe and efficient flight."),
18
- ("How do airlines handle overbooking?", "Airlines handle overbooking by offering incentives to passengers who voluntarily give up their seats. If no one volunteers, the airline may involuntarily deny boarding to some passengers and compensate them according to regulations."),
19
- ("What is the purpose of a frequent flyer program?", "The purpose of a frequent flyer program is to reward loyal customers by offering points or miles for each flight taken. These points can be redeemed for free flights, upgrades, or other perks, encouraging repeat business."),
20
- ("How do airlines calculate ticket prices?", "Airlines calculate ticket prices based on factors such as demand, competition, fuel costs, taxes, and the type of fare. Dynamic pricing models are often used to adjust prices in real-time based on market conditions."),
21
- ("What is the difference between economy, business, and first-class cabins?", "Economy class offers standard seating and amenities, business class provides more comfort and services, and first class offers the highest level of luxury, including spacious seats, gourmet meals, and personalized service."),
22
- ("How do airlines ensure safety during flight?", "Airlines ensure safety through rigorous maintenance schedules, pilot training, strict adherence to regulatory standards, and the use of advanced technology for navigation, communication, and monitoring systems."),
23
- ("What is the role of air traffic control in an airline operation?", "Air traffic control ensures the safe and orderly flow of air traffic by providing pilots with instructions and information, managing flight paths, and coordinating with other aircraft and ground services."),
24
- ("How do airlines handle baggage handling?", "Airlines handle baggage through a system of conveyor belts, scanners, and automated sorting systems. Baggage is tagged, tracked, and loaded onto the correct flight to ensure it reaches the destination with the passenger."),
25
- ("What is the process for canceling a flight ticket?", "The process for canceling a flight ticket involves contacting the airline or travel agent, providing the necessary details, and following the airline's cancellation policy, which may include fees and refund options."),
26
- ("How do airlines manage fuel efficiency?", "Airlines manage fuel efficiency through optimized flight paths, weight reduction, advanced engine technology, and operational practices such as reducing taxi times and using ground power instead of auxiliary power units."),
27
- ("What is the role of a flight attendant?", "A flight attendant's role is to ensure the safety and comfort of passengers during the flight. They provide assistance, serve meals and beverages, and respond to emergencies as needed."),
28
- ("How do airlines handle delays and cancellations?", "Airlines handle delays and cancellations by providing passengers with updated information, rebooking options, and compensation according to regulations. They also work to minimize disruptions through contingency planning."),
29
- ("What is the purpose of a black box in an aircraft?", "The black box, or flight data recorder, is used to record flight data and cockpit conversations. It helps investigators determine the cause of an accident or incident by providing detailed information about the flight."),
30
- ("How do airlines ensure customer satisfaction?", "Airlines ensure customer satisfaction by providing high-quality service, addressing complaints promptly, offering loyalty programs, and continuously improving their products and services based on customer feedback."),
31
- ("What is the role of a ground crew in an airline?", "The ground crew handles various tasks such as aircraft cleaning, fueling, baggage loading, and passenger assistance. They ensure that the aircraft is ready for departure and provide support during boarding and deplaning."),
32
- ("How do airlines manage partnerships and alliances?", "Airlines manage partnerships and alliances by collaborating with other carriers to expand their network, share resources, and offer seamless travel experiences to passengers through codesharing and reciprocal benefits."),
33
- ("What is the process for checking in for a flight?", "The process for checking in for a flight involves providing identification and booking details at the airport counter, kiosk, or online. Passengers receive their boarding pass and baggage tags, and their luggage is checked in."),
34
- ("How do airlines handle in-flight entertainment?", "Airlines handle in-flight entertainment by offering a variety of options such as movies, TV shows, music, games, and Wi-Fi. The content is provided through seatback screens, personal devices, or streaming services."),
35
- ("What is the role of a pilot in an airline?", "The pilot's role is to safely operate the aircraft, navigate to the destination, and ensure the safety of passengers and crew. They are responsible for pre-flight checks, takeoff, landing, and managing in-flight operations."),
36
- ("How do airlines manage cargo operations?", "Airlines manage cargo operations by using dedicated cargo aircraft or passenger aircraft with cargo holds. They handle freight booking, loading, tracking, and delivery to ensure timely and secure transportation of goods."),
37
- ("What is the purpose of a boarding pass?", "The boarding pass serves as proof of a passenger's reservation and authorization to board the flight. It contains details such as the passenger's name, flight number, seat assignment, and boarding gate."),
38
- ("How do airlines handle passenger complaints?", "Airlines handle passenger complaints by providing channels for feedback, such as customer service hotlines, email, or in-person assistance. They investigate the issue, offer solutions, and work to improve their services based on complaints."),
39
- ("What is the role of a flight dispatcher?", "A flight dispatcher assists in planning and monitoring flights. They provide pilots with flight plans, weather updates, and other critical information to ensure a safe and efficient operation."),
40
- ("How do airlines manage airport slots?", "Airlines manage airport slots by applying for and securing permission to operate at specific times and gates. Slot allocation is based on factors such as demand, airport capacity, and regulatory requirements."),
41
- ("What is the process for changing a flight ticket?", "The process for changing a flight ticket involves contacting the airline or travel agent, providing the necessary details, and following the airline's change policy, which may include fees and fare differences."),
42
- ("How do airlines handle in-flight meals?", "Airlines handle in-flight meals by partnering with caterers to prepare and deliver meals based on the flight duration, route, and passenger preferences. Meals are served by flight attendants during the flight."),
43
- ("What is the role of a baggage handler?", "A baggage handler's role is to load and unload baggage from the aircraft, ensuring it is correctly tagged and sorted. They also handle lost or delayed baggage claims and coordinate with other ground staff."),
44
- ("How do airlines manage loyalty program partnerships?", "Airlines manage loyalty program partnerships by collaborating with hotels, car rental companies, and other businesses to offer points-earning and redemption opportunities across multiple industries, enhancing the value of the program."),
45
- ("What is the purpose of a flight plan?", "The purpose of a flight plan is to provide detailed information about the flight, including the route, altitude, speed, and fuel requirements. It is used by pilots and air traffic control to ensure safe and efficient operations."),
46
- ("How do airlines handle passenger data privacy?", "Airlines handle passenger data privacy by adhering to regulations such as GDPR and CCPA. They implement data protection measures, secure storage systems, and provide transparency about how data is collected and used."),
47
- ("What is the role of a gate agent?", "A gate agent's role is to assist passengers with boarding and deplaning, verify boarding passes, and manage the boarding process. They also handle any last-minute changes or issues related to the flight."),
48
- ("How do airlines manage aircraft maintenance?", "Airlines manage aircraft maintenance through scheduled checks, inspections, and repairs. They follow strict regulatory standards and use advanced technology to ensure the aircraft remains airworthy and safe."),
49
- ("What is the purpose of a crew briefing?", "The purpose of a crew briefing is to provide pilots, flight attendants, and other crew members with essential information about the flight, including safety procedures, weather conditions, and any special instructions."),
50
- ("How do airlines handle passenger health and safety during the pandemic?", "Airlines handle passenger health and safety during the pandemic by implementing measures such as mask mandates, enhanced cleaning protocols, air filtration systems, social distancing, and health screenings."),
51
- ("What is the role of a flight engineer?", "A flight engineer's role is to monitor and manage the aircraft's systems, including engines, fuel, and navigation. They assist the pilot in ensuring the aircraft operates safely and efficiently, especially on older or larger planes."),
52
- ("How do airlines manage seasonal demand fluctuations?", "Airlines manage seasonal demand fluctuations by adjusting flight schedules, adding or reducing capacity, and offering promotional fares. They also use data analytics to predict demand and optimize operations accordingly."),
53
- ("What is the purpose of a baggage claim ticket?", "The purpose of a baggage claim ticket is to provide proof of ownership and tracking for checked luggage. It helps passengers identify their bags and assists airlines in locating lost or delayed baggage."),
54
- ("How do airlines handle passenger rebooking after a cancellation?", "Airlines handle passenger rebooking after a cancellation by offering alternative flight options, waiving change fees, and providing compensation according to regulations. They prioritize customer convenience and minimize disruptions."),
55
- ("What is the role of a flight operations manager?", "A flight operations manager oversees the planning and execution of flight operations. They ensure compliance with regulations, manage crew schedules, and coordinate with other departments to maintain efficiency and safety."),
56
- ("How do airlines manage aircraft turnaround time?", "Airlines manage aircraft turnaround time by optimizing ground operations, such as baggage loading, cleaning, and refueling. Efficient coordination between ground staff and crew helps minimize delays between flights."),
57
- ("What is the purpose of a crew rest facility?", "The purpose of a crew rest facility is to provide pilots and flight attendants with a place to rest and recover during long flights. These facilities ensure that crew members remain alert and fit to operate the aircraft safely."),
58
- ("How do airlines handle passenger seating assignments?", "Airlines handle passenger seating assignments by offering options for pre-selection, assigning seats based on fare class, or allowing passengers to choose seats at check-in. They also manage upgrades and special requests, such as extra legroom or companion seating."),
59
- ("What is the role of a flight simulator?", "A flight simulator is used for pilot training and testing. It provides a realistic environment to practice flying, handle emergencies, and familiarize themselves with aircraft systems without the risks of actual flight."),
60
- ("How do airlines manage cargo security?", "Airlines manage cargo security by implementing strict screening processes, using advanced scanning technology, and adhering to international regulations. They also work with security agencies to prevent unauthorized or hazardous materials from being transported."),
61
- ("What is the purpose of a crew scheduling system?", "The purpose of a crew scheduling system is to optimize the assignment of pilots and flight attendants to flights. It ensures compliance with labor regulations, maximizes efficiency, and minimizes costs while maintaining safety standards."),
62
- ("How do airlines handle passenger check-in kiosks?", "Airlines handle passenger check-in kiosks by providing self-service options that allow passengers to print boarding passes, select seats, and check luggage. These kiosks reduce wait times and streamline the check-in process."),
63
- ("What is the role of a flight data analyst?", "A flight data analyst collects and analyzes data related to flight operations, such as performance, delays, and fuel consumption. They provide insights to improve efficiency, safety, and profitability for the airline."),
64
- ("How do airlines manage passenger boarding?", "Airlines manage passenger boarding by using strategies such as zone boarding, pre-boarding for special needs passengers, and mobile boarding passes. Efficient boarding processes help reduce delays and improve the overall travel experience."),
65
- ("What is the purpose of a crew briefing room?", "The purpose of a crew briefing room is to provide a space for pilots and flight attendants to receive pre-flight instructions, review safety procedures, and discuss any special requirements for the upcoming flight."),
66
- ("How do airlines handle passenger feedback?", "Airlines handle passenger feedback by collecting data through surveys, social media, and customer service channels. They analyze feedback to identify areas for improvement and implement changes to enhance the passenger experience."),
67
- ("What is the role of a flight operations coordinator?", "A flight operations coordinator assists in planning and monitoring flight schedules. They ensure that all operational requirements are met, coordinate with various departments, and provide support to the flight crew."),
68
- ("How do airlines manage aircraft cleaning?", "Airlines manage aircraft cleaning by using specialized teams to perform deep cleans between flights. They follow strict hygiene protocols, use eco-friendly cleaning products, and ensure compliance with health and safety regulations."),
69
- ("What is the purpose of a crew rest period?", "The purpose of a crew rest period is to ensure that pilots and flight attendants are well-rested and fit to operate the aircraft safely. Rest periods are regulated by aviation authorities to prevent fatigue and maintain safety standards."),
70
- ("How do airlines handle passenger upgrades?", "Airlines handle passenger upgrades by offering them through loyalty programs, last-minute promotions, or as a reward for frequent flyers. Upgrades may include moving to business or first class for enhanced comfort and services."),
71
- ("What is the role of a flight operations director?", "A flight operations director oversees all aspects of flight operations, including scheduling, safety, and compliance. They ensure that the airline meets its operational goals while maintaining high safety and service standards."),
72
- ("How do airlines manage aircraft refueling?", "Airlines manage aircraft refueling by coordinating with ground service providers and fuel suppliers. They ensure that the correct amount of fuel is loaded based on flight distance, weather conditions, and regulatory requirements."),
73
- ("What is the purpose of a crew rest area?", "The purpose of a crew rest area is to provide a comfortable and secure space for pilots and flight attendants to rest during long flights. These areas are designed to ensure that crew members remain alert and fit to operate the aircraft safely."),
74
- ("How do airlines handle passenger special requests?", "Airlines handle passenger special requests by offering options such as dietary accommodations, wheelchair assistance, or seating preferences. They work to fulfill these requests to enhance the passenger experience and ensure comfort."),
75
- ("What is the role of a flight operations analyst?", "A flight operations analyst reviews and analyzes data related to flight operations, such as performance metrics, delays, and fuel consumption. They provide insights to improve efficiency, safety, and profitability for the airline."),
76
- ("How do airlines manage passenger baggage tracking?", "Airlines manage passenger baggage tracking by using barcode or RFID tags, automated sorting systems, and real-time monitoring. These technologies help ensure that baggage is loaded onto the correct flight and reaches the destination with the passenger."),
77
- ("What is the purpose of a crew scheduling manager?", "The purpose of a crew scheduling manager is to oversee the assignment of pilots and flight attendants to flights. They ensure compliance with labor regulations, maximize efficiency, and minimize costs while maintaining safety standards."),
78
- ("How do airlines handle passenger check-in queues?", "Airlines handle passenger check-in queues by offering self-service kiosks, mobile check-in options, and dedicated staff to assist passengers. Efficient queue management helps reduce wait times and improve the overall travel experience."),
79
- ("What is the role of a flight operations specialist?", "A flight operations specialist assists in planning and monitoring flight schedules. They ensure that all operational requirements are met, coordinate with various departments, and provide support to the flight crew."),
80
- ("How do airlines manage aircraft de-icing?", "Airlines manage aircraft de-icing by using specialized equipment and chemicals to remove ice and snow from the aircraft's surface. This process ensures safe takeoff and prevents ice buildup that could affect flight performance."),
81
- ("What is the purpose of a crew briefing checklist?", "The purpose of a crew briefing checklist is to ensure that all essential information is communicated to the flight crew before departure. It includes safety procedures, weather updates, and any special instructions for the flight."),
82
- ("How do airlines handle passenger health screenings?", "Airlines handle passenger health screenings by implementing measures such as temperature checks, health declaration forms, and contact tracing. These measures help ensure the safety of passengers and crew during the pandemic."),
83
- ("What is the role of a flight operations assistant?", "A flight operations assistant supports the flight operations team by handling administrative tasks, coordinating with various departments, and providing logistical support. They ensure that all operational requirements are met efficiently."),
84
- ("How do airlines manage aircraft parking?", "Airlines manage aircraft parking by coordinating with airport authorities to secure appropriate gates and parking spots. They ensure that aircraft are parked safely and efficiently, minimizing delays and disruptions."),
85
- ("What is the purpose of a crew rest policy?", "The purpose of a crew rest policy is to ensure that pilots and flight attendants are well-rested and fit to operate the aircraft safely. These policies are regulated by aviation authorities to prevent fatigue and maintain safety standards."),
86
- ("How do airlines handle passenger seating changes?", "Airlines handle passenger seating changes by offering options for seat selection, upgrades, or reassignments. They work to accommodate special requests and ensure that passengers are seated in a manner that maximizes comfort and safety."),
87
- ("What is the role of a flight operations coordinator?", "A flight operations coordinator assists in planning and monitoring flight schedules. They ensure that all operational requirements are met, coordinate with various departments, and provide support to the flight crew."),
88
- ("How do airlines manage aircraft maintenance scheduling?", "Airlines manage aircraft maintenance scheduling by using advanced software to plan and track maintenance activities. They ensure that all checks and repairs are performed on time, maintaining the aircraft's airworthiness and safety.")
89
- ]
90
-
91
- # Step 4: Define a function to generate answers
92
- def ask_question(question):
93
- # Check if the question is in the dataset
94
- for q, a in qa_data:
95
- if question.lower() == q.lower():
96
- return a
97
-
98
- # If the question is not in the dataset, generate a response using the model
99
  input_text = f"Question: {question} Answer:"
100
- input_ids = tokenizer.encode(input_text, return_tensors="pt")
101
 
102
- with torch.no_grad():
103
- output = model.generate(
104
- input_ids,
105
- max_length=1024,
106
- num_return_sequences=1,
107
- no_repeat_ngram_size=2,
108
- do_sample=True,
109
- top_k=50,
110
- top_p=0.95,
111
- temperature=0.7
112
- )
113
-
114
- answer = tokenizer.decode(output[0], skip_special_tokens=True)
115
- answer = answer.split("Answer:")[-1].strip()
116
-
117
- # If the model fails to generate a meaningful response, return a default message
118
- if not answer or answer.lower() == "answer:":
119
- return "I'm sorry, but I don't have information about that. I can only provide information related to airline systems."
120
 
121
- return answer
 
 
122
 
123
- # Step 5: Create the Gradio interface
124
- def chat_interface(input_text, chat_history=[]):
125
- # Handle greetings
126
- greetings = ["hi", "hello", "aslam o alikum"]
127
- if input_text.strip().lower() in greetings:
128
- bot_response = "Hello! How can I assist you with airline-related questions?"
129
- else:
130
- # Handle other questions
131
- bot_response = ask_question(input_text)
132
-
133
- # Update chat history
134
- chat_history.append((input_text, bot_response))
135
-
136
- # Return updated chat history
137
- return chat_history, chat_history
138
 
139
- # Step 6: Launch the Gradio app
140
- with gr.Blocks() as iface:
141
- gr.Markdown("# Airline Chatbot\nAsk me anything about airlines!")
142
-
143
- # Chatbot component
144
- chat_history = gr.Chatbot(label="Chatbot")
145
-
146
- # Input textbox and send button
 
 
 
 
 
 
 
 
147
  with gr.Row():
148
- user_input = gr.Textbox(label="You", placeholder="Type your message here...", lines=2)
149
- send_button = gr.Button("Send")
150
 
151
- # Examples
152
- gr.Examples(
153
- examples=[
154
- "How do airlines manage fuel efficiency?",
155
- "How does an airline manage its flight schedules?",
156
- "How do airlines handle passenger seating changes?",
157
- "What is the purpose of a crew rest area?"
158
- ],
159
- inputs=user_input
160
- )
161
 
162
- # Connect the send button to the chat interface
163
- send_button.click(
164
- fn=chat_interface,
165
- inputs=[user_input, chat_history],
166
- outputs=[chat_history, chat_history]
167
- )
168
 
169
- iface.launch(debug=True)
 
 
 
 
1
  import torch
2
+ from transformers import GPT2LMHeadModel, GPT2Tokenizer
3
+ import gradio as gr
4
 
5
+ # Load the fine-tuned model and tokenizer from Hugging Face
6
+ model_name = "Rehman1603/Travel_fine_tuned_gpt2_model_final" # Replace with your Hugging Face model path
7
+ model = GPT2LMHeadModel.from_pretrained(model_name)
8
+ tokenizer = GPT2Tokenizer.from_pretrained(model_name)
9
 
10
+ # Move model to the appropriate device
11
+ device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
12
+ model.to(device)
13
 
14
+ # Function to generate responses
15
+ def generate_response(question, max_length=1024, temperature=0.5, top_k=50, top_p=0.95):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  input_text = f"Question: {question} Answer:"
17
+ input_ids = tokenizer.encode(input_text, return_tensors="pt").to(device)
18
 
19
+ # Generate response
20
+ output = model.generate(
21
+ input_ids,
22
+ max_length=max_length,
23
+ temperature=temperature,
24
+ #num_return_sequences=1,
25
+ #no_repeat_ngram_size=2,
26
+ top_k=top_k,
27
+ top_p=top_p,
28
+ do_sample=True,
29
+ pad_token_id=tokenizer.eos_token_id
30
+ )
 
 
 
 
 
 
31
 
32
+ # Decode and return the response
33
+ response = tokenizer.decode(output[0], skip_special_tokens=True)
34
+ return response.split("Answer:")[-1].strip()
35
 
36
+ # Gradio Interface
37
+ def chat_interface(question, history):
38
+ response = generate_response(question)
39
+ history = history or []
40
+ history.append((question, response))
41
+ return history, history
 
 
 
 
 
 
 
 
 
42
 
43
+ # Test questions
44
+ test_questions = [
45
+ "Hi",
46
+ "What is the duration of the Economy Umrah Package?",
47
+ "Good morning",
48
+ "What is the distance of hotels from Haram in Package 4?",
49
+ "What is the price of a 14-night Umrah package with air tickets in Package 1",
50
+ "What is the price of a 20-night Umrah package without air tickets?"
51
+ ]
52
+
53
+ # Create Gradio interface
54
+ with gr.Blocks() as demo:
55
+ chatbot = gr.Chatbot()
56
+ state = gr.State()
57
+ with gr.Row():
58
+ txt = gr.Textbox(show_label=False, placeholder="Enter your question here")
59
  with gr.Row():
60
+ submit_btn = gr.Button("Submit")
61
+ clear_btn = gr.Button("Clear")
62
 
63
+ # Example questions
64
+ examples = gr.Examples(examples=test_questions, inputs=txt)
 
 
 
 
 
 
 
 
65
 
66
+ # Event handling
67
+ submit_btn.click(chat_interface, [txt, state], [chatbot, state])
68
+ clear_btn.click(lambda: None, None, chatbot, queue=False)
 
 
 
69
 
70
+ # Launch the interface
71
+ demo.launch(debug=True)