Update app.py
Browse files
app.py
CHANGED
@@ -1,17 +1,163 @@
|
|
1 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
2 |
import requests
|
3 |
-
|
|
|
4 |
from langchain.vectorstores import FAISS
|
5 |
-
from langchain_community.chat_models.huggingface import ChatHuggingFace
|
6 |
-
from langchain.schema import SystemMessage, HumanMessage, AIMessage
|
7 |
from langchain_community.llms import HuggingFaceEndpoint
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
|
9 |
-
|
10 |
-
|
|
|
|
|
|
|
11 |
|
12 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
|
14 |
-
# Set up Hugging Face model
|
15 |
llm = HuggingFaceEndpoint(
|
16 |
repo_id="HuggingFaceH4/starchat2-15b-v0.1",
|
17 |
task="text-generation",
|
@@ -24,98 +170,334 @@ llm = HuggingFaceEndpoint(
|
|
24 |
)
|
25 |
chat_model = ChatHuggingFace(llm=llm)
|
26 |
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
AIMessage(content="I'm great thank you. How can I help you?")
|
31 |
-
]
|
32 |
|
33 |
-
def
|
34 |
-
|
35 |
-
|
36 |
-
if not message.strip():
|
37 |
-
return "Enter a valid message.", None
|
38 |
-
|
39 |
-
if mode == "Chat-Message":
|
40 |
-
result_text = chat_message(message)
|
41 |
-
elif mode == "Web-Search":
|
42 |
-
result_text = web_search(message)
|
43 |
-
elif mode == "Chart-Generator":
|
44 |
-
result_text, result_image = chart_generator(message)
|
45 |
-
else:
|
46 |
-
result_text = "Select a valid mode."
|
47 |
-
|
48 |
-
return result_text, result_image
|
49 |
|
50 |
-
def
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
56 |
response = chat_model.invoke(messages)
|
57 |
messages.append(response.content)
|
58 |
-
|
59 |
-
if len(messages) >= 6:
|
60 |
-
messages = messages[-6:]
|
61 |
-
|
62 |
-
return f"IT-Assistant: {response.content}"
|
63 |
|
64 |
-
|
65 |
-
|
66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
similar_docs = db.similarity_search(message, k=3)
|
68 |
-
|
69 |
if similar_docs:
|
70 |
source_knowledge = "\n".join([x.page_content for x in similar_docs])
|
71 |
else:
|
72 |
source_knowledge = ""
|
73 |
-
|
74 |
augmented_prompt = f"""
|
75 |
If the answer to the next query is not contained in the Search, say 'No Answer Is Available' and then just give guidance for the query.
|
76 |
Query: {message}
|
77 |
Search:
|
78 |
{source_knowledge}
|
79 |
"""
|
80 |
-
|
81 |
-
|
82 |
-
messages.append(
|
83 |
-
|
84 |
-
response = chat_model.invoke(messages)
|
85 |
messages.append(response.content)
|
86 |
-
|
87 |
-
if len(messages) >= 6:
|
88 |
-
messages = messages[-6:]
|
89 |
-
|
90 |
-
return f"IT-Assistant: {response.content}"
|
91 |
|
92 |
-
|
93 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
94 |
|
|
|
95 |
chart_url = f"https://quickchart.io/natural/{message}"
|
96 |
response = requests.get(chart_url)
|
97 |
|
98 |
if response.status_code == 200:
|
99 |
-
|
|
|
100 |
|
101 |
prompt = HumanMessage(content=message_with_description)
|
102 |
messages.append(prompt)
|
103 |
|
104 |
-
|
105 |
-
messages.append(
|
106 |
-
|
107 |
-
if len(messages) >=
|
108 |
-
messages = messages[-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
|
110 |
-
|
|
|
111 |
else:
|
112 |
-
|
113 |
-
|
114 |
-
|
115 |
-
|
116 |
-
|
117 |
-
|
118 |
-
|
119 |
-
|
120 |
-
|
121 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import PyPDF2
|
2 |
+
import os
|
3 |
+
from bs4 import BeautifulSoup
|
4 |
+
import tempfile
|
5 |
+
import csv
|
6 |
+
import json
|
7 |
+
import xml.etree.ElementTree as ET
|
8 |
+
import docx
|
9 |
+
import pptx
|
10 |
+
import openpyxl
|
11 |
+
import re
|
12 |
+
import nltk
|
13 |
+
import time
|
14 |
import requests
|
15 |
+
import gradio as gr
|
16 |
+
from nltk.tokenize import word_tokenize
|
17 |
from langchain.vectorstores import FAISS
|
|
|
|
|
18 |
from langchain_community.llms import HuggingFaceEndpoint
|
19 |
+
from langchain.embeddings import SentenceTransformerEmbeddings
|
20 |
+
from langchain.schema import SystemMessage, HumanMessage, AIMessage
|
21 |
+
from langchain_community.chat_models.huggingface import ChatHuggingFace
|
22 |
+
from youtube_transcript_api import YouTubeTranscriptApi
|
23 |
+
from youtube_transcript_api._errors import NoTranscriptFound, TranscriptsDisabled, VideoUnavailable
|
24 |
+
nltk.download('punkt')
|
25 |
+
nltk.download('omw-1.4')
|
26 |
+
nltk.download('wordnet')
|
27 |
|
28 |
+
def read_csv(file_path):
|
29 |
+
with open(file_path, 'r', encoding='utf-8', errors='ignore', newline='') as csvfile:
|
30 |
+
csv_reader = csv.reader(csvfile)
|
31 |
+
csv_data = [row for row in csv_reader]
|
32 |
+
return ' '.join([' '.join(row) for row in csv_data])
|
33 |
|
34 |
+
def read_text(file_path):
|
35 |
+
with open(file_path, 'r', encoding='utf-8', errors='ignore', newline='') as f:
|
36 |
+
return f.read()
|
37 |
+
|
38 |
+
def read_pdf(file_path):
|
39 |
+
text_data = []
|
40 |
+
with open(file_path, 'rb') as pdf_file:
|
41 |
+
pdf_reader = PyPDF2.PdfReader(pdf_file)
|
42 |
+
for page in pdf_reader.pages:
|
43 |
+
text_data.append(page.extract_text())
|
44 |
+
return '\n'.join(text_data)
|
45 |
+
|
46 |
+
def read_docx(file_path):
|
47 |
+
doc = docx.Document(file_path)
|
48 |
+
return '\n'.join([paragraph.text for paragraph in doc.paragraphs])
|
49 |
+
|
50 |
+
def read_pptx(file_path):
|
51 |
+
ppt = pptx.Presentation(file_path)
|
52 |
+
text_data = ''
|
53 |
+
for slide in ppt.slides:
|
54 |
+
for shape in slide.shapes:
|
55 |
+
if hasattr(shape, "text"):
|
56 |
+
text_data += shape.text + '\n'
|
57 |
+
return text_data
|
58 |
+
|
59 |
+
def read_xlsx(file_path):
|
60 |
+
workbook = openpyxl.load_workbook(file_path)
|
61 |
+
sheet = workbook.active
|
62 |
+
text_data = ''
|
63 |
+
for row in sheet.iter_rows(values_only=True):
|
64 |
+
text_data += ' '.join([str(cell) for cell in row if cell is not None]) + '\n'
|
65 |
+
return text_data
|
66 |
+
|
67 |
+
def read_json(file_path):
|
68 |
+
with open(file_path, 'r') as f:
|
69 |
+
json_data = json.load(f)
|
70 |
+
return json.dumps(json_data)
|
71 |
+
|
72 |
+
def read_html(file_path):
|
73 |
+
with open(file_path, 'r') as f:
|
74 |
+
html_content = f.read()
|
75 |
+
soup = BeautifulSoup(html_content, 'html.parser')
|
76 |
+
return soup
|
77 |
+
|
78 |
+
def read_xml(file_path):
|
79 |
+
tree = ET.parse(file_path)
|
80 |
+
root = tree.getroot()
|
81 |
+
return ET.tostring(root, encoding='unicode')
|
82 |
+
|
83 |
+
def process_youtube_video(url, languages=['en', 'ar']):
|
84 |
+
if 'youtube.com/watch' in url or 'youtu.be/' in url:
|
85 |
+
try:
|
86 |
+
if "v=" in url:
|
87 |
+
video_id = url.split("v=")[1].split("&")[0]
|
88 |
+
elif "youtu.be/" in url:
|
89 |
+
video_id = url.split("youtu.be/")[1].split("?")[0]
|
90 |
+
else:
|
91 |
+
return "Invalid YouTube video URL. Please provide a valid YouTube video link."
|
92 |
+
|
93 |
+
response = requests.get(f"http://img.youtube.com/vi/{video_id}/mqdefault.jpg")
|
94 |
+
if response.status_code != 200:
|
95 |
+
return "Video doesn't exist."
|
96 |
+
|
97 |
+
transcript_data = []
|
98 |
+
for lang in languages:
|
99 |
+
try:
|
100 |
+
transcript = YouTubeTranscriptApi.get_transcript(video_id, languages=[lang])
|
101 |
+
transcript_data.append(' '.join([entry['text'] for entry in transcript]))
|
102 |
+
except (NoTranscriptFound, TranscriptsDisabled, VideoUnavailable):
|
103 |
+
continue
|
104 |
+
|
105 |
+
return ' '.join(transcript_data) if transcript_data else "Please choose a YouTube video with available English or Arabic transcripts."
|
106 |
+
|
107 |
+
except Exception as e:
|
108 |
+
return f"An error occurred: {e}"
|
109 |
+
else:
|
110 |
+
return "Invalid YouTube URL. Please provide a valid YouTube link."
|
111 |
+
|
112 |
+
def read_web_page(url):
|
113 |
+
result = requests.get(url)
|
114 |
+
if result.status_code == 200:
|
115 |
+
src = result.content
|
116 |
+
soup = BeautifulSoup(src, 'html.parser')
|
117 |
+
text_data = ''
|
118 |
+
for p in soup.find_all('p'):
|
119 |
+
text_data += p.get_text() + '\n'
|
120 |
+
return text_data
|
121 |
+
else:
|
122 |
+
return "Please provide a valid webpage link"
|
123 |
+
|
124 |
+
def read_data(file_path_or_url, languages=['en', 'ar']):
|
125 |
+
if file_path_or_url.endswith('.csv'):
|
126 |
+
return read_csv(file_path_or_url)
|
127 |
+
elif file_path_or_url.endswith('.txt'):
|
128 |
+
return read_text(file_path_or_url)
|
129 |
+
elif file_path_or_url.endswith('.pdf'):
|
130 |
+
return read_pdf(file_path_or_url)
|
131 |
+
elif file_path_or_url.endswith('.docx'):
|
132 |
+
return read_docx(file_path_or_url)
|
133 |
+
elif file_path_or_url.endswith('.pptx'):
|
134 |
+
return read_pptx(file_path_or_url)
|
135 |
+
elif file_path_or_url.endswith('.xlsx'):
|
136 |
+
return read_xlsx(file_path_or_url)
|
137 |
+
elif file_path_or_url.endswith('.json'):
|
138 |
+
return read_json(file_path_or_url)
|
139 |
+
elif file_path_or_url.endswith('.html'):
|
140 |
+
return read_html(file_path_or_url)
|
141 |
+
elif file_path_or_url.endswith('.xml'):
|
142 |
+
return read_xml(file_path_or_url)
|
143 |
+
elif 'youtube.com/watch' in file_path_or_url or 'youtu.be/' in file_path_or_url:
|
144 |
+
return process_youtube_video(file_path_or_url, languages)
|
145 |
+
elif file_path_or_url.startswith('http'):
|
146 |
+
return read_web_page(file_path_or_url)
|
147 |
+
else:
|
148 |
+
return "Unsupported type or format."
|
149 |
+
|
150 |
+
def normalize_text(text):
|
151 |
+
text = re.sub("\*?", "", text)
|
152 |
+
text = text.lower()
|
153 |
+
text = text.strip()
|
154 |
+
punctuation = '''!()[]{};:'"\<>/?$%^&*_`~='''
|
155 |
+
for punc in punctuation:
|
156 |
+
text = text.replace(punc, "")
|
157 |
+
text = re.sub(r'[A-Za-z0-9]*@[A-Za-z]*\.?[A-Za-z0-9]*', "", text)
|
158 |
+
words = word_tokenize(text)
|
159 |
+
return ' '.join(words)
|
160 |
|
|
|
161 |
llm = HuggingFaceEndpoint(
|
162 |
repo_id="HuggingFaceH4/starchat2-15b-v0.1",
|
163 |
task="text-generation",
|
|
|
170 |
)
|
171 |
chat_model = ChatHuggingFace(llm=llm)
|
172 |
|
173 |
+
model_name = "sentence-transformers/all-mpnet-base-v2"
|
174 |
+
embedding_llm = SentenceTransformerEmbeddings(model_name=model_name)
|
175 |
+
db = FAISS.load_local("faiss_index", embedding_llm, allow_dangerous_deserialization=True)
|
|
|
|
|
176 |
|
177 |
+
def print_like_dislike(x: gr.LikeData):
|
178 |
+
print(x.index, x.value, x.liked)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
179 |
|
180 |
+
def user(user_message, history):
|
181 |
+
if not len(user_message):
|
182 |
+
raise gr.Error("Chat messages cannot be empty")
|
183 |
+
return "", history + [[user_message, None]]
|
184 |
+
|
185 |
+
def user2(user_message, history, link):
|
186 |
+
if not len(user_message) or not len(link):
|
187 |
+
raise gr.Error("Chat messages or links cannot be empty")
|
188 |
+
combined_message = f"{link}\n{user_message}"
|
189 |
+
return "", history + [[combined_message, None]], link
|
190 |
+
|
191 |
+
def user3(user_message, history, file_path):
|
192 |
+
if not len(user_message) or not file_path:
|
193 |
+
raise gr.Error("Chat messages or flies cannot be empty")
|
194 |
+
combined_message = f"{file_path}\n{user_message}"
|
195 |
+
return "", history + [[combined_message, None]], file_path
|
196 |
+
|
197 |
+
def Chat_Message(history):
|
198 |
+
messages = [
|
199 |
+
SystemMessage(content="You are a helpful assistant."),
|
200 |
+
HumanMessage(content="Hi AI, how are you today?"),
|
201 |
+
AIMessage(content="I'm great thank you. How can I help you?")]
|
202 |
+
|
203 |
+
message=HumanMessage(content=history[-1][0])
|
204 |
+
messages.append(message)
|
205 |
response = chat_model.invoke(messages)
|
206 |
messages.append(response.content)
|
|
|
|
|
|
|
|
|
|
|
207 |
|
208 |
+
if len(messages) >= 8:
|
209 |
+
messages = messages[-8:]
|
210 |
+
|
211 |
+
history[-1][1] = ""
|
212 |
+
for character in response.content:
|
213 |
+
history[-1][1] += character
|
214 |
+
time.sleep(0.0025)
|
215 |
+
yield history
|
216 |
+
|
217 |
+
def Web_Search(history):
|
218 |
+
messages = [
|
219 |
+
SystemMessage(content="You are a helpful assistant."),
|
220 |
+
HumanMessage(content="Hi AI, how are you today?"),
|
221 |
+
AIMessage(content="I'm great thank you. How can I help you?")]
|
222 |
+
|
223 |
+
message=history[-1][0]
|
224 |
+
|
225 |
similar_docs = db.similarity_search(message, k=3)
|
226 |
+
|
227 |
if similar_docs:
|
228 |
source_knowledge = "\n".join([x.page_content for x in similar_docs])
|
229 |
else:
|
230 |
source_knowledge = ""
|
231 |
+
|
232 |
augmented_prompt = f"""
|
233 |
If the answer to the next query is not contained in the Search, say 'No Answer Is Available' and then just give guidance for the query.
|
234 |
Query: {message}
|
235 |
Search:
|
236 |
{source_knowledge}
|
237 |
"""
|
238 |
+
|
239 |
+
msg==HumanMessage(content=augmented_prompt)
|
240 |
+
messages.append(msg)
|
241 |
+
response = chat_model.invoke(msg)
|
|
|
242 |
messages.append(response.content)
|
|
|
|
|
|
|
|
|
|
|
243 |
|
244 |
+
if len(messages) >= 8:
|
245 |
+
messages = messages[-8:]
|
246 |
+
|
247 |
+
history[-1][1] = ""
|
248 |
+
for character in response.content:
|
249 |
+
history[-1][1] += character
|
250 |
+
time.sleep(0.0025)
|
251 |
+
yield history
|
252 |
+
|
253 |
+
def Chart_Generator(history):
|
254 |
+
messages = [
|
255 |
+
SystemMessage(content="You are a helpful assistant."),
|
256 |
+
HumanMessage(content="Hi AI, how are you today?"),
|
257 |
+
AIMessage(content="I'm great thank you. How can I help you?")
|
258 |
+
]
|
259 |
|
260 |
+
message = history[-1][0]
|
261 |
chart_url = f"https://quickchart.io/natural/{message}"
|
262 |
response = requests.get(chart_url)
|
263 |
|
264 |
if response.status_code == 200:
|
265 |
+
image_html = f'<img src="{chart_url}" alt="Generated Chart" style="display: block; margin: auto; max-width: 100%; max-height: 100%;">'
|
266 |
+
message_with_description = f"Describe and analyse the content of this chart: {chart_url}"
|
267 |
|
268 |
prompt = HumanMessage(content=message_with_description)
|
269 |
messages.append(prompt)
|
270 |
|
271 |
+
res = chat_model.invoke(messages)
|
272 |
+
messages.append(res.content)
|
273 |
+
|
274 |
+
if len(messages) >= 8:
|
275 |
+
messages = messages[-8:]
|
276 |
+
|
277 |
+
combined_content = f'{image_html}<br>{res.content}'
|
278 |
+
else:
|
279 |
+
response_text = "Can't generate this image. Please provide valid chart details."
|
280 |
+
combined_content = response_text
|
281 |
+
|
282 |
+
history[-1][1] = ""
|
283 |
+
for character in combined_content:
|
284 |
+
history[-1][1] += character
|
285 |
+
time.sleep(0.0025)
|
286 |
+
yield history
|
287 |
+
|
288 |
+
def Link_Scratch(history):
|
289 |
+
messages = [
|
290 |
+
SystemMessage(content="You are a helpful assistant."),
|
291 |
+
HumanMessage(content="Hi AI, how are you today?"),
|
292 |
+
AIMessage(content="I'm great thank you. How can I help you?")
|
293 |
+
]
|
294 |
+
|
295 |
+
combined_message = history[-1][0]
|
296 |
+
|
297 |
+
link = ""
|
298 |
+
user_message = ""
|
299 |
+
if "\n" in combined_message:
|
300 |
+
link, user_message = combined_message.split("\n", 1)
|
301 |
+
link = link.strip()
|
302 |
+
user_message = user_message.strip()
|
303 |
+
|
304 |
+
result = read_data(link)
|
305 |
+
|
306 |
+
if result in ["Unsupported type or format.", "Please provide a valid webpage link",
|
307 |
+
"Invalid YouTube URL. Please provide a valid YouTube link.",
|
308 |
+
"Please choose a YouTube video with available English or Arabic transcripts.",
|
309 |
+
"Invalid YouTube video URL. Please provide a valid YouTube video link."]:
|
310 |
+
response_message = result
|
311 |
+
else:
|
312 |
+
content_data = normalize_text(result)
|
313 |
+
if not content_data:
|
314 |
+
response_message = "The provided link is empty or does not contain any meaningful words."
|
315 |
+
else:
|
316 |
+
augmented_prompt = f"""
|
317 |
+
If the answer to the next query is not contained in the Link Content, say 'No Answer Is Available' and then just give guidance for the query.
|
318 |
+
Query: {user_message}
|
319 |
+
Link Content:
|
320 |
+
{content_data}
|
321 |
+
"""
|
322 |
+
message = HumanMessage(content=augmented_prompt)
|
323 |
+
messages.append(message)
|
324 |
+
response = chat_model.invoke(messages)
|
325 |
+
messages.append(response.content)
|
326 |
+
|
327 |
+
if len(messages) >= 1:
|
328 |
+
messages = messages[-1:]
|
329 |
+
|
330 |
+
response_message = response.content
|
331 |
+
|
332 |
+
history[-1][1] = ""
|
333 |
+
for character in response_message:
|
334 |
+
history[-1][1] += character
|
335 |
+
time.sleep(0.0025)
|
336 |
+
yield history
|
337 |
+
|
338 |
+
def insert_line_breaks(text, every=8):
|
339 |
+
return '\n'.join(text[i:i+every] for i in range(0, len(text), every))
|
340 |
+
|
341 |
+
def display_file_name(file):
|
342 |
+
supported_extensions = ['.csv', '.txt', '.pdf', '.docx', '.pptx', '.xlsx', '.json', '.html', '.xml']
|
343 |
+
file_extension = os.path.splitext(file.name)[1]
|
344 |
+
if file_extension.lower() in supported_extensions:
|
345 |
+
file_name = os.path.basename(file.name)
|
346 |
+
file_name_with_breaks = insert_line_breaks(file_name)
|
347 |
+
icon_url = "https://img.icons8.com/ios-filled/50/0000FF/file.png"
|
348 |
+
return f"<div style='display: flex; align-items: center;'><img src='{icon_url}' alt='file-icon' style='width: 20px; height: 20px; margin-right: 5px;'><b style='color:blue;'>{file_name_with_breaks}</b></div>"
|
349 |
+
else:
|
350 |
+
raise gr.Error("( Supported File Types Only : PDF , CSV , TXT , DOCX , PPTX , XLSX , JSON , HTML , XML )")
|
351 |
+
|
352 |
+
def File_Interact(history,filepath):
|
353 |
+
messages = [
|
354 |
+
SystemMessage(content="You are a helpful assistant."),
|
355 |
+
HumanMessage(content="Hi AI, how are you today?"),
|
356 |
+
AIMessage(content="I'm great thank you. How can I help you?")]
|
357 |
+
|
358 |
+
combined_message = history[-1][0]
|
359 |
+
|
360 |
+
link = ""
|
361 |
+
user_message = ""
|
362 |
+
if "\n" in combined_message:
|
363 |
+
link, user_message = combined_message.split("\n", 1)
|
364 |
+
user_message = user_message.strip()
|
365 |
+
|
366 |
+
result = read_data(filepath)
|
367 |
|
368 |
+
if result == "Unsupported type or format.":
|
369 |
+
response_message = result
|
370 |
else:
|
371 |
+
content_data = normalize_text(result)
|
372 |
+
if not content_data:
|
373 |
+
response_message = "The file is empty or does not contain any meaningful words."
|
374 |
+
else:
|
375 |
+
augmented_prompt = f"""
|
376 |
+
If the answer to the next query is not contained in the File Content, say 'No Answer Is Available' and then just give guidance for the query.
|
377 |
+
Query: {user_message}
|
378 |
+
File Content:
|
379 |
+
{content_data}
|
380 |
+
"""
|
381 |
+
message = HumanMessage(content=augmented_prompt)
|
382 |
+
messages.append(message)
|
383 |
+
response = chat_model.invoke(messages)
|
384 |
+
messages.append(response.content)
|
385 |
+
|
386 |
+
if len(messages) >= 1:
|
387 |
+
messages = messages[-1:]
|
388 |
+
|
389 |
+
response_message = response.content
|
390 |
+
|
391 |
+
history[-1][1] = ""
|
392 |
+
for character in response_message:
|
393 |
+
history[-1][1] += character
|
394 |
+
time.sleep(0.0025)
|
395 |
+
yield history
|
396 |
+
|
397 |
+
with gr.Blocks(theme=gr.themes.Soft()) as demo:
|
398 |
+
with gr.Row():
|
399 |
+
gr.Markdown("""<span style='font-weight: bold; color: blue; font-size: large;'>Choose Your Mode</span>""")
|
400 |
+
gr.Markdown("""<div style='margin-left: -120px;'><span style='font-weight: bold; color: blue; font-size: xx-large;'>IT ASSISTANT</span></div>""")
|
401 |
+
|
402 |
+
with gr.Tab("Chat-Message"):
|
403 |
+
chatbot = gr.Chatbot(
|
404 |
+
[],
|
405 |
+
elem_id="chatbot",
|
406 |
+
bubble_full_width=False,
|
407 |
+
height=500,
|
408 |
+
placeholder="<span style='font-weight: bold; color: blue; font-size: x-large;'>Feel Free To Ask Me Anything Or Start A Conversation On Any Topic...</span>"
|
409 |
+
)
|
410 |
+
with gr.Row():
|
411 |
+
msg = gr.Textbox(show_label=False, placeholder="Type a message...", scale=10, container=False)
|
412 |
+
submit = gr.Button("➡️Send", scale=1)
|
413 |
+
|
414 |
+
clear = gr.ClearButton([msg, chatbot])
|
415 |
+
|
416 |
+
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=True).then(Chat_Message, chatbot, chatbot)
|
417 |
+
submit.click(user, [msg, chatbot], [msg, chatbot], queue=True).then(Chat_Message, chatbot, chatbot)
|
418 |
+
chatbot.like(print_like_dislike, None, None)
|
419 |
+
|
420 |
+
with gr.Tab("Web-Search"):
|
421 |
+
chatbot = gr.Chatbot(
|
422 |
+
[],
|
423 |
+
elem_id="chatbot",
|
424 |
+
bubble_full_width=False,
|
425 |
+
height=500,
|
426 |
+
placeholder="<span style='font-weight: bold; color: blue; font-size: x-large;'>Demand What You Seek, And I'll Search The Web For The Most Relevant Information...</span>"
|
427 |
+
)
|
428 |
+
with gr.Row():
|
429 |
+
msg = gr.Textbox(show_label=False, placeholder="Type a message...", scale=10, container=False)
|
430 |
+
submit = gr.Button("➡️Send", scale=1)
|
431 |
+
|
432 |
+
clear = gr.ClearButton([msg, chatbot])
|
433 |
+
|
434 |
+
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=True).then(Web_Search, chatbot, chatbot)
|
435 |
+
submit.click(user, [msg, chatbot], [msg, chatbot], queue=True).then(Web_Search, chatbot, chatbot)
|
436 |
+
chatbot.like(print_like_dislike, None, None)
|
437 |
+
|
438 |
+
with gr.Tab("Chart-Generator"):
|
439 |
+
chatbot = gr.Chatbot(
|
440 |
+
[],
|
441 |
+
elem_id="chatbot",
|
442 |
+
bubble_full_width=False,
|
443 |
+
height=500,
|
444 |
+
placeholder="<span style='font-weight: bold; color: blue; font-size: x-large;'>Request Any Chart Or Graph By Giving The Data Or A Description, And I'll Create It...</span>"
|
445 |
+
)
|
446 |
+
|
447 |
+
with gr.Row():
|
448 |
+
msg = gr.Textbox(show_label=False, placeholder="Type a message...", scale=10, container=False)
|
449 |
+
submit = gr.Button("➡️Send", scale=1)
|
450 |
+
|
451 |
+
clear = gr.ClearButton([msg, chatbot])
|
452 |
+
|
453 |
+
msg.submit(user, [msg, chatbot], [msg, chatbot], queue=True).then(Chart_Generator, chatbot, chatbot)
|
454 |
+
submit.click(user, [msg, chatbot], [msg, chatbot], queue=True).then(Chart_Generator, chatbot, chatbot)
|
455 |
+
chatbot.like(print_like_dislike, None, None)
|
456 |
+
|
457 |
+
with gr.Tab("Link-Scratch"):
|
458 |
+
chatbot = gr.Chatbot(
|
459 |
+
[],
|
460 |
+
elem_id="chatbot",
|
461 |
+
bubble_full_width=False,
|
462 |
+
height=500,
|
463 |
+
placeholder="<span style='font-weight: bold; color: blue; font-size: x-large;'>Provide A Link Of Web page Or YouTube Video And Inquire About Its Details...</span>"
|
464 |
+
)
|
465 |
+
|
466 |
+
with gr.Row():
|
467 |
+
msg1 = gr.Textbox(show_label=False, placeholder="Paste your link...", scale=4, container=False)
|
468 |
+
msg2 = gr.Textbox(show_label=False, placeholder="Type a message...", scale=7, container=False)
|
469 |
+
submit = gr.Button("➡️Send", scale=1)
|
470 |
+
|
471 |
+
clear = gr.ClearButton([msg2, chatbot, msg1])
|
472 |
+
|
473 |
+
msg1.submit(user2, [msg2, chatbot, msg1], [msg2, chatbot, msg1], queue=True).then(Link_Scratch, chatbot, chatbot)
|
474 |
+
msg2.submit(user2, [msg2, chatbot, msg1], [msg2, chatbot, msg1], queue=True).then(Link_Scratch, chatbot, chatbot)
|
475 |
+
submit.click(user2, [msg2, chatbot, msg1], [msg2, chatbot, msg1], queue=True).then(Link_Scratch, chatbot, chatbot)
|
476 |
+
chatbot.like(print_like_dislike, None, None)
|
477 |
+
|
478 |
+
with gr.Tab("File-Interact"):
|
479 |
+
chatbot = gr.Chatbot(
|
480 |
+
[],
|
481 |
+
elem_id="chatbot",
|
482 |
+
bubble_full_width=False,
|
483 |
+
height=500,
|
484 |
+
placeholder="<span style='font-weight: bold; color: blue; font-size: x-large;'>Upload A File And Explore Questions Related To Its Content...</span><br>( Supported File Types Only : PDF , CSV , TXT , DOCX , PPTX , XLSX , JSON , HTML , XML )"
|
485 |
+
)
|
486 |
+
|
487 |
+
with gr.Column():
|
488 |
+
with gr.Row():
|
489 |
+
filepath = gr.UploadButton("Upload a file", file_count="single", scale=1)
|
490 |
+
msg = gr.Textbox(show_label=False, placeholder="Type a message...", scale=7, container=False)
|
491 |
+
submit = gr.Button("➡️Send", scale=1)
|
492 |
+
with gr.Row():
|
493 |
+
file_output = gr.HTML("<div style='height: 20px; width: 30px;'></div>")
|
494 |
+
clear = gr.ClearButton([msg, filepath, chatbot,file_output],scale=6)
|
495 |
+
|
496 |
+
filepath.upload(display_file_name, inputs=filepath, outputs=file_output)
|
497 |
+
|
498 |
+
msg.submit(user3, [msg, chatbot, file_output], [msg, chatbot, file_output], queue=True).then(File_Interact, [chatbot, filepath],chatbot)
|
499 |
+
submit.click(user3, [msg, chatbot, file_output], [msg, chatbot, file_output], queue=True).then(File_Interact, [chatbot, filepath],chatbot)
|
500 |
+
chatbot.like(print_like_dislike, None, None)
|
501 |
+
|
502 |
+
demo.queue(max_size=5)
|
503 |
+
demo.launch(max_file_size="5mb",show_api=False)
|