Spaces:
Sleeping
Sleeping
Upload app.py
Browse files
app.py
ADDED
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from sentence_transformers import SentenceTransformer, util
|
3 |
+
import openai
|
4 |
+
import os
|
5 |
+
import os
|
6 |
+
os.environ["TOKENIZERS_PARALLELISM"] = "false"
|
7 |
+
|
8 |
+
|
9 |
+
# Initialize paths and model identifiers for easy configuration and maintenance
|
10 |
+
filename = "output_country_details.txt" # Path to the file storing country-specific details
|
11 |
+
retrieval_model_name = 'output/sentence-transformer-finetuned/'
|
12 |
+
|
13 |
+
openai.api_key = 'sk-proj-BVO7g5ig8PKdlQwDCZSeT3BlbkFJAvilYAEcPFbA0XOjz7ce'
|
14 |
+
|
15 |
+
|
16 |
+
|
17 |
+
# Attempt to load the necessary models and provide feedback on success or failure
|
18 |
+
try:
|
19 |
+
retrieval_model = SentenceTransformer(retrieval_model_name)
|
20 |
+
print("Models loaded successfully.")
|
21 |
+
except Exception as e:
|
22 |
+
print(f"Failed to load models: {e}")
|
23 |
+
|
24 |
+
def load_and_preprocess_text(filename):
|
25 |
+
"""
|
26 |
+
Load and preprocess text from a file, removing empty lines and stripping whitespace.
|
27 |
+
"""
|
28 |
+
try:
|
29 |
+
with open(filename, 'r', encoding='utf-8') as file:
|
30 |
+
segments = [line.strip() for line in file if line.strip()]
|
31 |
+
print("Text loaded and preprocessed successfully.")
|
32 |
+
return segments
|
33 |
+
except Exception as e:
|
34 |
+
print(f"Failed to load or preprocess text: {e}")
|
35 |
+
return []
|
36 |
+
|
37 |
+
segments = load_and_preprocess_text(filename)
|
38 |
+
|
39 |
+
def find_relevant_segment(user_query, segments):
|
40 |
+
"""
|
41 |
+
Find the most relevant text segment for a user's query using cosine similarity among sentence embeddings.
|
42 |
+
This version tries to match country names in the query with those in the segments.
|
43 |
+
"""
|
44 |
+
try:
|
45 |
+
# Lowercase the query for better matching
|
46 |
+
lower_query = user_query.lower()
|
47 |
+
# Filter segments to include only those containing country names mentioned in the query
|
48 |
+
country_segments = [seg for seg in segments if any(country.lower() in seg.lower() for country in ['Guatemala', 'Mexico', 'U.S.', 'United States'])]
|
49 |
+
|
50 |
+
# If no specific country segments found, default to general matching
|
51 |
+
if not country_segments:
|
52 |
+
country_segments = segments
|
53 |
+
|
54 |
+
query_embedding = retrieval_model.encode(lower_query)
|
55 |
+
segment_embeddings = retrieval_model.encode(country_segments)
|
56 |
+
similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
|
57 |
+
best_idx = similarities.argmax()
|
58 |
+
return country_segments[best_idx]
|
59 |
+
except Exception as e:
|
60 |
+
print(f"Error in finding relevant segment: {e}")
|
61 |
+
return ""
|
62 |
+
|
63 |
+
|
64 |
+
def generate_response(user_query, relevant_segment):
|
65 |
+
"""
|
66 |
+
Generate a response using the latest GPT-3 model available via OpenAI's API.
|
67 |
+
"""
|
68 |
+
try:
|
69 |
+
prompt = f"Thank you for your question! Here's additional information: {relevant_segment}"
|
70 |
+
response = openai.Completion.create(
|
71 |
+
engine="gpt-3.5-turbo-instruct", # Updated to a currently supported engine
|
72 |
+
prompt=prompt,
|
73 |
+
max_tokens=150,
|
74 |
+
temperature=0.7,
|
75 |
+
top_p=1,
|
76 |
+
frequency_penalty=0,
|
77 |
+
presence_penalty=0
|
78 |
+
)
|
79 |
+
return response.choices[0].text.strip()
|
80 |
+
except Exception as e:
|
81 |
+
print(f"Error in generating response: {e}")
|
82 |
+
return f"Error in generating response: {e}"
|
83 |
+
|
84 |
+
|
85 |
+
|
86 |
+
# Define and configure the Gradio application interface to interact with users.
|
87 |
+
# Define and configure the Gradio application interface to interact with users.
|
88 |
+
def query_model(question):
|
89 |
+
"""
|
90 |
+
Process a question, find relevant information, and generate a response, specifically for U.S. visa questions.
|
91 |
+
"""
|
92 |
+
if question == "":
|
93 |
+
return "Welcome to VisaBot! Ask me anything about U.S. visa processes."
|
94 |
+
relevant_segment = find_relevant_segment(question, segments)
|
95 |
+
if not relevant_segment:
|
96 |
+
return "Could not find U.S.-specific information. Please refine your question."
|
97 |
+
response = generate_response(question, relevant_segment)
|
98 |
+
return response
|
99 |
+
|
100 |
+
|
101 |
+
# Define the welcome message and specific topics and countries the chatbot can provide information about.
|
102 |
+
welcome_message = """
|
103 |
+
# Welcome to VISABOT!
|
104 |
+
|
105 |
+
## Your AI-driven visa assistant for all travel-related queries.
|
106 |
+
"""
|
107 |
+
|
108 |
+
topics = """
|
109 |
+
### Feel Free to ask me anything from the topics below!
|
110 |
+
- Visa issuance
|
111 |
+
- Documents needed
|
112 |
+
- Application process
|
113 |
+
- Processing time
|
114 |
+
- Recommended Vaccines
|
115 |
+
- Health Risks
|
116 |
+
- Healthcare Facilities
|
117 |
+
- Currency Information
|
118 |
+
- Embassy Information
|
119 |
+
- Allowed stay
|
120 |
+
"""
|
121 |
+
|
122 |
+
countries = """
|
123 |
+
### Our chatbot can currently answer questions for these countries!
|
124 |
+
- π¨π³ China
|
125 |
+
- π«π· France
|
126 |
+
- π¬πΉ Guatemala
|
127 |
+
- π±π§ Lebanon
|
128 |
+
- π²π½ Mexico
|
129 |
+
- π΅π Philippines
|
130 |
+
- π·πΈ Serbia
|
131 |
+
- πΈπ± Sierra Leone
|
132 |
+
- πΏπ¦ South Africa
|
133 |
+
- π»π³ Vietnam
|
134 |
+
"""
|
135 |
+
|
136 |
+
# Define and configure the Gradio application interface to interact with users.
|
137 |
+
def query_model(question):
|
138 |
+
"""
|
139 |
+
Process a question, find relevant information, and generate a response.
|
140 |
+
|
141 |
+
Args:
|
142 |
+
question (str): User's input question.
|
143 |
+
|
144 |
+
Returns:
|
145 |
+
str: Generated response or a default welcome message if no question is provided.
|
146 |
+
"""
|
147 |
+
if question == "":
|
148 |
+
return welcome_message
|
149 |
+
relevant_segment = find_relevant_segment(question, segments)
|
150 |
+
response = generate_response(question, relevant_segment)
|
151 |
+
return response
|
152 |
+
|
153 |
+
# Setup the Gradio Blocks interface with custom layout components
|
154 |
+
with gr.Blocks() as demo:
|
155 |
+
gr.Markdown(welcome_message) # Display the formatted welcome message
|
156 |
+
with gr.Row():
|
157 |
+
with gr.Column():
|
158 |
+
gr.Markdown(topics) # Show the topics on the left side
|
159 |
+
with gr.Column():
|
160 |
+
gr.Markdown(countries) # Display the list of countries on the right side
|
161 |
+
with gr.Row():
|
162 |
+
img = gr.Image(os.path.join(os.getcwd(), "poster.png"), width=500) # Include an image for visual appeal
|
163 |
+
with gr.Row():
|
164 |
+
with gr.Column():
|
165 |
+
question = gr.Textbox(label="Your question", placeholder="What do you want to ask about?")
|
166 |
+
answer = gr.Textbox(label="VisaBot Response", placeholder="VisaBot will respond here...", interactive=False, lines=10)
|
167 |
+
submit_button = gr.Button("Submit")
|
168 |
+
submit_button.click(fn=query_model, inputs=question, outputs=answer)
|
169 |
+
|
170 |
+
# Launch the Gradio app to allow user interaction
|
171 |
+
demo.launch(share= True)
|
172 |
+
|