hibalaz commited on
Commit
486cd93
1 Parent(s): 2900610

Upload 2 files

Browse files
Files changed (2) hide show
  1. app.py +138 -0
  2. requirements.txt +8 -0
app.py ADDED
@@ -0,0 +1,138 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from sentence_transformers import SentenceTransformer, util
3
+ from transformers import pipeline, GPT2Tokenizer
4
+ import os
5
+
6
+ # Define paths and model identifiers for easy reference and maintenance
7
+ filename = "output_country_details.txt" # Filename for stored country details
8
+ retrieval_model_name = 'output/sentence-transformer-finetuned/'
9
+ gpt2_model_name = "gpt2" # Identifier for the GPT-2 model used
10
+ tokenizer = GPT2Tokenizer.from_pretrained(gpt2_model_name)
11
+
12
+ # Load models and handle potential failures gracefully
13
+ try:
14
+ retrieval_model = SentenceTransformer(retrieval_model_name)
15
+ gpt_model = pipeline("text-generation", model=gpt2_model_name)
16
+ print("Models loaded successfully.")
17
+ except Exception as e:
18
+ print(f"Failed to load models: {e}")
19
+
20
+ def load_and_preprocess_text(filename):
21
+ """
22
+ Load text data from a file and preprocess it by stripping whitespace and ignoring empty lines.
23
+
24
+ Args:
25
+ filename (str): Path to the file containing text data.
26
+
27
+ Returns:
28
+ list of str: Preprocessed lines of text from the file.
29
+ """
30
+ try:
31
+ with open(filename, 'r', encoding='utf-8') as file:
32
+ segments = [line.strip() for line in file if line.strip()]
33
+ print("Text loaded and preprocessed successfully.")
34
+ return segments
35
+ except Exception as e:
36
+ print(f"Failed to load or preprocess text: {e}")
37
+ return []
38
+
39
+ segments = load_and_preprocess_text(filename)
40
+
41
+ def find_relevant_segment(user_query, segments):
42
+ """
43
+ Identify the most relevant text segment from a list based on a user's query using sentence embeddings.
44
+
45
+ Args:
46
+ user_query (str): User's input query.
47
+ segments (list of str): List of text segments to search from.
48
+
49
+ Returns:
50
+ str: The text segment that best matches the query.
51
+ """
52
+ try:
53
+ query_embedding = retrieval_model.encode(user_query)
54
+ segment_embeddings = retrieval_model.encode(segments)
55
+ similarities = util.pytorch_cos_sim(query_embedding, segment_embeddings)[0]
56
+ best_idx = similarities.argmax()
57
+ print("Relevant segment found:", segments[best_idx])
58
+ return segments[best_idx]
59
+ except Exception as e:
60
+ print(f"Error finding relevant segment: {e}")
61
+ return ""
62
+
63
+ def generate_response(user_query, relevant_segment):
64
+ """
65
+ Generate a response to a user's query using a text generation model based on a relevant text segment.
66
+
67
+ Args:
68
+ user_query (str): The user's query.
69
+ relevant_segment (str): The segment of text that is relevant to the query.
70
+
71
+ Returns:
72
+ str: A response generated from the model.
73
+ """
74
+ try:
75
+ prompt = f"Thank you for your question! This is an additional fact about your topic: {relevant_segment}"
76
+ max_tokens = len(tokenizer(prompt)['input_ids']) + 50
77
+ response = gpt_model(prompt, max_length=max_tokens, temperature=0.25)[0]['generated_text']
78
+ response_cleaned = clean_up_response(response, relevant_segment)
79
+ return response_cleaned
80
+ except Exception as e:
81
+ print(f"Error generating response: {e}")
82
+ return ""
83
+
84
+ def clean_up_response(response, segments):
85
+ """
86
+ Clean and format the generated response by removing empty sentences and repetitive parts.
87
+
88
+ Args:
89
+ response (str): The raw response generated by the model.
90
+ segments (str): The text segment used to generate the response.
91
+
92
+ Returns:
93
+ str: Cleaned and formatted response.
94
+ """
95
+ sentences = response.split('.')
96
+ cleaned_sentences = []
97
+ for sentence in sentences:
98
+ if sentence.strip() and sentence.strip() not in segments and sentence.strip() not in cleaned_sentences:
99
+ cleaned_sentences.append(sentence.strip())
100
+ cleaned_response = '. '.join(cleaned_sentences).strip()
101
+ if cleaned_response and not cleaned_response.endswith((".", "!", "?")):
102
+ cleaned_response += "."
103
+ return cleaned_response
104
+
105
+ # Gradio interface and application logic
106
+ def query_model(question):
107
+ """
108
+ Process a question through the model and return the response.
109
+
110
+ Args:
111
+ question (str): The question submitted by the user.
112
+
113
+ Returns:
114
+ str: Generated response or welcome message if no question is provided.
115
+ """
116
+ if question == "":
117
+ return welcome_message
118
+ relevant_segment = find_relevant_segment(question, segments)
119
+ response = generate_response(question, relevant_segment)
120
+ return response
121
+
122
+ with gr.Blocks() as demo:
123
+ gr.Markdown(welcome_message)
124
+ with gr.Row():
125
+ with gr.Column():
126
+ gr.Markdown(topics)
127
+ with gr.Column():
128
+ gr.Markdown(countries)
129
+ with gr.Row():
130
+ img = gr.Image(os.path.join(os.getcwd(), "final.png"), width=500)
131
+ with gr.Row():
132
+ with gr.Column():
133
+ question = gr.Textbox(label="Your question", placeholder="What do you want to ask about?")
134
+ answer = gr.Textbox(label="VisaBot Response", placeholder="VisaBot will respond here...", interactive=False, lines=10)
135
+ submit_button = gr.Button("Submit")
136
+ submit_button.click(fn=query_model, inputs=question, outputs=answer)
137
+
138
+ demo.launch()
requirements.txt ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ gradio==2.2.15
2
+ sentence-transformers==2.1.0
3
+ transformers==4.15.0
4
+ tokenizers>=0.10.1,<0.11
5
+ datasets==1.14.0
6
+ pandas==1.3.3
7
+ tokenizers==0.10.0
8
+ torch==1.10.0