Spaces:
Runtime error
Runtime error
Update app.py
Browse files
app.py
CHANGED
@@ -1,50 +1,20 @@
|
|
1 |
-
from langchain_together import ChatTogether
|
2 |
-
|
3 |
-
"""# ⭐ LLM model with togithor Ai
|
4 |
-
|
5 |
-
"""
|
6 |
-
|
7 |
-
from langchain_community.llms import Together
|
8 |
-
|
9 |
-
import os
|
10 |
-
os.environ['TOGETHER_API_KEY'] = 'e83925ff068ab5e4598a56f68385fd37144469f50eec94f5c2e6647798f1be9e'
|
11 |
-
|
12 |
-
response = Together(
|
13 |
-
model="meta-llama/Meta-Llama-3.1-70B-Instruct-Turbo",
|
14 |
-
max_tokens=1524,
|
15 |
-
temperature=0.2,
|
16 |
-
# top_p=1.1,
|
17 |
-
# top_k=40,
|
18 |
-
|
19 |
-
repetition_penalty=1.1,
|
20 |
-
together_api_key=os.environ.get('TOGETHER_API_KEY')
|
21 |
-
)
|
22 |
-
|
23 |
-
"""# ⭐ Pinecone Vectore Database
|
24 |
-
|
25 |
-
"""
|
26 |
-
|
27 |
-
|
28 |
-
from langchain_pinecone import PineconeVectorStore
|
29 |
-
from langchain_openai import OpenAIEmbeddings
|
30 |
-
import os
|
31 |
-
os.environ['PINECONE_API_KEY']='f7413055-9b13-4bbc-8c92-56132e034bff'
|
32 |
-
|
33 |
-
em=OpenAIEmbeddings(api_key='sk-Q43XYIJudIE0Q7e5t23U5CjA5dMNYRGlMOhfm6VTA2T3BlbkFJn3a9zqCCIdjRcV7QKmkok3n0F1BL_KS0OzkLEbjXgA',model="text-embedding-3-small")
|
34 |
-
pc=PineconeVectorStore(index_name="learnverse",embedding=em)
|
35 |
-
|
36 |
-
"""#⭐ Summarization"""
|
37 |
-
|
38 |
import gradio as gr
|
|
|
|
|
39 |
from transformers import BitsAndBytesConfig, pipeline
|
40 |
-
from langchain_huggingface import HuggingFacePipeline
|
41 |
from langchain_core.prompts import ChatPromptTemplate
|
42 |
from langchain_core.output_parsers import StrOutputParser
|
|
|
|
|
43 |
|
44 |
-
|
|
|
|
|
|
|
45 |
|
46 |
-
|
47 |
-
|
|
|
48 |
|
49 |
this is the context:
|
50 |
```{context}```
|
@@ -63,82 +33,24 @@ prompt = """
|
|
63 |
### Conclusion
|
64 |
- Suggest any potential actions, solutions, or recommendations.
|
65 |
|
66 |
-
|
67 |
-
|
68 |
this is the summary:
|
69 |
-
|
70 |
-
"""
|
71 |
-
summary_prompt = ChatPromptTemplate.from_template(
|
72 |
-
prompt
|
73 |
-
)
|
74 |
-
|
75 |
-
summary_llm_chain = summary_prompt | response | StrOutputParser()
|
76 |
-
|
77 |
-
# create a function that upload pdf file and the summary chain get the file
|
78 |
-
from langchain_core.runnables import RunnablePassthrough
|
79 |
-
|
80 |
-
summary_pdf_chain = {"context": RunnablePassthrough()} | summary_llm_chain
|
81 |
-
|
82 |
-
"""# Query Prompt"""
|
83 |
-
|
84 |
-
q_prompt = """
|
85 |
-
you are the greatest Question answering model ,you will get a question and answer the question based on the context.
|
86 |
-
|
87 |
-
this is the context:
|
88 |
-
```{context}```
|
89 |
-
|
90 |
-
this is the questions: {question}
|
91 |
-
"""
|
92 |
-
query_prompt = ChatPromptTemplate.from_template(
|
93 |
-
q_prompt
|
94 |
-
)
|
95 |
-
|
96 |
-
query_llm_chain = query_prompt | response | StrOutputParser()
|
97 |
-
|
98 |
-
from langchain_core.runnables import RunnablePassthrough
|
99 |
-
|
100 |
-
retriever = pc.as_retriever(
|
101 |
-
search_type="similarity",
|
102 |
-
search_kwargs={'k': 4}
|
103 |
-
)
|
104 |
-
|
105 |
-
query_rag_chain = {"context": retriever, "question": RunnablePassthrough()}|query_llm_chain
|
106 |
-
|
107 |
-
"""# ⭐ Extract Text From Pdf
|
108 |
-
|
109 |
"""
|
|
|
110 |
|
111 |
-
|
112 |
-
import time
|
113 |
-
|
114 |
def extract_text_from_pdf(file):
|
115 |
loader = PyPDFLoader(file)
|
116 |
pages = loader.load_and_split()
|
117 |
-
pc.from_documents(pages,index_name='learnverse',embedding=em)
|
118 |
-
|
119 |
text = ""
|
120 |
for page in pages:
|
121 |
-
|
122 |
-
text += page.page_content
|
123 |
return text
|
124 |
|
125 |
-
|
126 |
-
|
127 |
-
|
128 |
-
from elevenlabs import VoiceSettings, play
|
129 |
-
from elevenlabs.client import ElevenLabs
|
130 |
-
import ffmpeg
|
131 |
-
import IPython.display as ipd
|
132 |
-
import os
|
133 |
-
|
134 |
-
# Make sure to import the required classes
|
135 |
-
# sk_dcb140eeca914ac72a06ae91c4e9742b2c559c7451831c71
|
136 |
-
def text_to_speech_stream(text: str):
|
137 |
-
ELEVENLABS_API_KEY = 'sk_3ec0ff46017e49189870e2dc9c51f87939d6e2d8cc823316'
|
138 |
-
client = ElevenLabs(
|
139 |
-
api_key=ELEVENLABS_API_KEY,
|
140 |
-
)
|
141 |
-
|
142 |
response = client.text_to_speech.convert(
|
143 |
voice_id="jBpfuIE2acCO8z3wKNLl",
|
144 |
optimize_streaming_latency="0",
|
@@ -159,459 +71,65 @@ def text_to_speech_stream(text: str):
|
|
159 |
audio_data.write(chunk)
|
160 |
|
161 |
audio_data.seek(0)
|
162 |
-
|
163 |
-
# Create 'samples' directory if it doesn't exist
|
164 |
if not os.path.exists('samples'):
|
165 |
os.makedirs('samples')
|
166 |
|
167 |
-
# Write the audio data to a file
|
168 |
with open('samples/output.mp3', 'wb') as f:
|
169 |
f.write(audio_data.read())
|
170 |
|
171 |
return 'samples/output.mp3'
|
172 |
|
173 |
-
|
174 |
-
|
175 |
-
"""
|
176 |
-
|
177 |
-
# prompt for extracting three topics
|
178 |
-
|
179 |
-
topics_prompt="""
|
180 |
-
|
181 |
-
Extract the Main Topics:
|
182 |
-
|
183 |
-
Analyze the following text and identify the one main clear topic that related to AI like robot and VR etc Then, translate the topic into a simplified format that can be understood . The goal is to ensure that the topic would be easy and clear so the model can accurately generate a 3d shape based on the simplified concepts.
|
184 |
-
|
185 |
-
Text: {context}
|
186 |
-
Answer:
|
187 |
-
|
188 |
-
"""
|
189 |
-
|
190 |
-
tp = ChatPromptTemplate.from_template(topics_prompt)
|
191 |
-
|
192 |
-
topic_chain = tp | response | StrOutputParser()
|
193 |
-
|
194 |
-
"""# Evauluation summary"""
|
195 |
-
|
196 |
-
|
197 |
-
import wandb
|
198 |
-
wandb.login()
|
199 |
-
# 956c40e3fd97485d68ec80c6841faec28368fd34
|
200 |
-
|
201 |
-
from rouge import Rouge
|
202 |
-
|
203 |
def evaluate_summary(generated_summary):
|
204 |
-
wandb.init(
|
205 |
-
|
206 |
-
|
207 |
-
"""
|
208 |
-
Evaluates the generated summary against a list of reference summaries using the ROUGE metric.
|
209 |
-
|
210 |
-
Parameters:
|
211 |
-
- reference_summaries (list of str): A list of reference summaries (ground truth).
|
212 |
-
- generated_summary (str): The summary generated by the model.
|
213 |
-
|
214 |
-
Returns:
|
215 |
-
- dict: A dictionary containing the average ROUGE-1, ROUGE-2, and ROUGE-L scores.
|
216 |
-
"""
|
217 |
-
# Variable 1
|
218 |
-
summary1 = """
|
219 |
-
Introduction: The context discusses the concept of Artificial Intelligence (AI), its evolution, and its applications in various fields. AI is a branch of computer science that aims to create intelligent machines capable of performing tasks that typically require human intelligence.
|
220 |
-
|
221 |
-
Section 1: Key Concepts
|
222 |
-
* Definition and Types of AI: AI can be classified into three types: Weak or Narrow AI, General AI, and Strong AI. Weak AI is the most widely used type, which can perform a pre-defined narrow set of instructions without exhibiting any thinking capability.
|
223 |
-
* Machine Learning and Deep Learning: Machine Learning (ML) is a subset of AI that enables computers to learn from data and past experiences. Deep Learning (DL) is a subdomain of ML that mimics the human nervous system and is used for image recognition, pattern recognition, and feature extraction.
|
224 |
-
* Applications of AI: AI has various applications in fields such as agriculture, business, education, entertainment, healthcare, and space exploration.
|
225 |
-
|
226 |
-
Section 2: Supporting Details
|
227 |
-
* Agriculture: AI is used in soil analysis, crop sowing, pest control, and crop harvesting. It has improved crop yields and reduced the use of chemical fertilizers.
|
228 |
-
* Healthcare: AI is used in medical diagnosis, image analysis, and patient monitoring. It has improved the accuracy of diagnosis and reduced the workload of healthcare professionals.
|
229 |
-
* Education: AI is used in personalized learning, adaptive assessments, and intelligent tutoring systems. It has improved student outcomes and increased access to education.
|
230 |
-
|
231 |
-
Section 3: Analysis and Interpretation
|
232 |
-
* Impact of AI: AI has the potential to transform various industries and improve the quality of life. However, it also raises concerns about job displacement, data privacy, and security.
|
233 |
-
* Challenges and Limitations: AI requires large amounts of data, computational power, and expertise. It also faces challenges related to interpretability, transparency, and accountability.
|
234 |
-
|
235 |
-
Conclusion: In conclusion, AI is a rapidly evolving field with various applications in different industries. While it has the potential to transform the world, it also raises concerns about its impact on society. To fully harness the benefits of AI, it is essential to address its challenges and limitations and ensure that its development and deployment are responsible and ethical.
|
236 |
-
"""
|
237 |
-
|
238 |
-
# Variable 2
|
239 |
-
summary2 = """
|
240 |
-
Introduction: The provided context is an introduction to Artificial Intelligence (AI), its subsets, and applications in various fields. The main purpose is to explore the capabilities, types, and domains of AI, as well as its impact on modern society.
|
241 |
-
|
242 |
-
Detailed Summary
|
243 |
-
|
244 |
-
Section 1: Key Concepts
|
245 |
-
* Definition and Types of AI: AI is a branch of computer science that enables computers to mimic human behavior. There are three types of AI: Weak or Narrow AI, General AI, and Strong AI.
|
246 |
-
* Domains of AI: The major domains of AI include neural networks, robotics, expert systems, fuzzy logic systems, and natural language processing (NLP).
|
247 |
-
* Subsets of AI: The two major subsets of AI are Machine Learning (ML) and Deep Learning (DL).
|
248 |
-
|
249 |
-
Section 2: Supporting Details
|
250 |
-
* Machine Learning: ML is a subset of AI that enables computers to learn from data and past experiences. There are three types of ML: Supervised Learning, Unsupervised Learning, and Reinforcement Learning.
|
251 |
-
* Deep Learning: DL is a subdomain of ML that mimics the human nervous system. It has various applications, including image recognition, natural language processing, and speech recognition.
|
252 |
-
* Applications of AI: AI has numerous applications in agriculture, business, education, entertainment, healthcare, and space exploration.
|
253 |
-
|
254 |
-
Section 3: Analysis and Interpretation
|
255 |
-
* Impact of AI: AI has transformed various industries and has the potential to revolutionize healthcare, education, and other sectors.
|
256 |
-
* Challenges and Limitations: AI faces challenges such as data accuracy, security, and interpretability. It also raises concerns about job displacement and bias.
|
257 |
-
* Future Directions: AI is expected to continue growing and improving, with potential applications in areas like genome editing, personalized medicine, and smart cities.
|
258 |
-
|
259 |
-
Conclusion: In conclusion, AI is a rapidly evolving field with numerous applications and potential benefits. However, it also raises concerns about data accuracy, security, and job displacement. As AI continues to grow and improve, it is essential to address these challenges and ensure that its benefits are equitably distributed.
|
260 |
-
"""
|
261 |
-
|
262 |
-
# Variable 3
|
263 |
-
summary3 = """
|
264 |
-
Introduction: The context discusses the concept of Artificial Intelligence (AI) and its applications in various fields. AI is a branch of computer science that enables computers to mimic human behavior, assisting humans in performance and decision-making. The context highlights the importance of AI in modern society, its subsets, and its impact on healthcare, education, business, and other sectors.
|
265 |
-
|
266 |
-
Section 1: Key Concepts
|
267 |
-
* Artificial Intelligence (AI): AI is a domain of computer science that deals with the development of intelligent computer systems capable of perceiving, analyzing, and reacting to inputs.
|
268 |
-
* Types of AI: AI can be classified into three types based on capabilities: Weak or Narrow AI, General AI, and Strong AI.
|
269 |
-
* Subsets of AI: Machine Learning (ML) and Deep Learning (DL) are two subsets of AI used to solve problems using high-performance algorithms and multilayer neural networks.
|
270 |
-
|
271 |
-
Section 2: Supporting Details
|
272 |
-
* Applications of AI: AI has various applications in healthcare, education, business, and other sectors, including medical diagnosis, image processing, web search engines, and finance.
|
273 |
-
* Machine Learning (ML): ML is a subset of AI that enables computers to learn from data and past experiences, improving performance and prediction accuracy.
|
274 |
-
* Deep Learning (DL): DL is a subdomain of ML that mimics the human nervous system, using neural networks to analyze and interpret data.
|
275 |
-
|
276 |
-
Section 3: Analysis and Interpretation
|
277 |
-
* Impact of AI: AI has transformed various sectors, including healthcare, education, and business, by improving efficiency, accuracy, and decision-making.
|
278 |
-
* Challenges and Limitations: AI faces challenges such as data accuracy, security, and interpretability, which need to be addressed to ensure its effective implementation.
|
279 |
-
* Future Directions: AI is expected to continue transforming various sectors, with potential applications in space exploration, smart cities, and transportation.
|
280 |
-
|
281 |
-
Conclusion: In conclusion, AI is a rapidly evolving field with significant implications for various sectors. Its subsets, ML and DL, have transformed the way we approach problems and make decisions. While AI faces challenges and limitations, its potential applications and benefits make it an essential technology for the future.
|
282 |
-
"""
|
283 |
-
|
284 |
-
|
285 |
-
# Create the list of reference summaries
|
286 |
-
reference_summaries = [summary1, summary2, summary3]
|
287 |
-
|
288 |
-
# Initialize the ROUGE evaluator
|
289 |
rouge = Rouge()
|
290 |
-
|
291 |
-
|
292 |
-
|
293 |
-
rouge_2 = {'r': 0, 'p': 0, 'f': 0}
|
294 |
-
rouge_l = {'r': 0, 'p': 0, 'f': 0}
|
295 |
-
|
296 |
-
# Evaluate each reference summary
|
297 |
-
i=0
|
298 |
for reference in reference_summaries:
|
299 |
scores = rouge.get_scores(generated_summary, reference)
|
300 |
-
i+=1
|
301 |
-
|
302 |
rouge_1['r'] += scores[0]['rouge-1']['r']
|
303 |
rouge_1['p'] += scores[0]['rouge-1']['p']
|
304 |
rouge_1['f'] += scores[0]['rouge-1']['f']
|
305 |
-
|
306 |
rouge_2['r'] += scores[0]['rouge-2']['r']
|
307 |
rouge_2['p'] += scores[0]['rouge-2']['p']
|
308 |
rouge_2['f'] += scores[0]['rouge-2']['f']
|
309 |
-
|
310 |
rouge_l['r'] += scores[0]['rouge-l']['r']
|
311 |
rouge_l['p'] += scores[0]['rouge-l']['p']
|
312 |
rouge_l['f'] += scores[0]['rouge-l']['f']
|
313 |
-
|
314 |
-
print("score #"+str(i))
|
315 |
-
print(scores)
|
316 |
-
# print(rouge_1)
|
317 |
-
# print(rouge_2)
|
318 |
-
# print(rouge_l)
|
319 |
-
|
320 |
-
# Calculate the average scores
|
321 |
num_references = len(reference_summaries)
|
322 |
rouge_1 = {key: value / num_references for key, value in rouge_1.items()}
|
323 |
rouge_2 = {key: value / num_references for key, value in rouge_2.items()}
|
324 |
rouge_l = {key: value / num_references for key, value in rouge_l.items()}
|
325 |
-
|
326 |
-
# Return the average scores in a dictionary
|
327 |
-
print('\n')
|
328 |
-
print("The Average Scores")
|
329 |
-
print('')
|
330 |
-
|
331 |
-
print(rouge_1)
|
332 |
-
print(rouge_2)
|
333 |
-
print(rouge_l)
|
334 |
-
print('\n\n\n')
|
335 |
-
|
336 |
-
|
337 |
-
|
338 |
wandb.log(rouge_1)
|
339 |
wandb.log(rouge_2)
|
340 |
wandb.log(rouge_l)
|
341 |
-
|
342 |
-
|
343 |
-
if rouge_1['p'] < 0.1 and rouge_2['p'] < 0.1 and rouge_l['p'] < 0.1:
|
344 |
-
wandb.alert(title='Low Precesion', text=f'Precesion {rouge_1["p"]},{rouge_2["p"]},{rouge_l["p"]} is below the acceptable theshold')
|
345 |
-
|
346 |
wandb.finish()
|
347 |
-
|
348 |
-
|
349 |
-
'ROUGE-2': rouge_2,
|
350 |
-
'ROUGE-L': rouge_l
|
351 |
-
}
|
352 |
-
|
353 |
-
"""# 🦾 Function Integrator"""
|
354 |
|
|
|
355 |
def process_question(file):
|
356 |
-
|
357 |
-
#pd_file is for giving the ai asist somthing short to create
|
358 |
-
# pd_file = "AI is very good"
|
359 |
-
|
360 |
-
|
361 |
pdffile = extract_text_from_pdf(file)
|
362 |
three_topics = topic_chain.invoke({"context": pdffile})
|
363 |
-
print("--------Three Topics------")
|
364 |
-
print(three_topics)
|
365 |
-
|
366 |
summary = summary_pdf_chain.invoke(pdffile)
|
367 |
-
print("\n--------Summary---------")
|
368 |
-
print(summary)
|
369 |
-
|
370 |
-
print("--------Evaluation Summary---------")
|
371 |
evaluation = evaluate_summary(summary)
|
372 |
-
|
373 |
-
|
374 |
-
|
375 |
-
|
376 |
audio_file = text_to_speech_stream(summary)
|
377 |
-
|
378 |
-
|
379 |
-
|
380 |
-
|
381 |
-
|
382 |
-
return summary,evaluation,
|
383 |
-
|
384 |
-
#
|
385 |
-
|
386 |
-
|
387 |
-
|
388 |
-
|
389 |
-
|
390 |
-
from transformers import AutoTokenizer, BitsAndBytesConfig, AutoModelForCausalLM
|
391 |
-
import torch
|
392 |
-
|
393 |
-
model_id = "meta-llama/LlamaGuard-7b"
|
394 |
-
guard_tokenizer = AutoTokenizer.from_pretrained(model_id)
|
395 |
-
|
396 |
-
bnb_config_guard = BitsAndBytesConfig(
|
397 |
-
load_in_4bit=True,
|
398 |
-
bnb_4bit_use_double_quant=True,
|
399 |
-
bnb_4bit_quant_type="nf4",
|
400 |
-
bnb_4bit_compute_dtype=torch.bfloat16,
|
401 |
-
# Allow offloading to CPU for parts of the model
|
402 |
-
load_in_8bit_fp32_cpu_offload=True
|
403 |
-
)
|
404 |
-
guard_model = AutoModelForCausalLM.from_pretrained(
|
405 |
-
model_id,
|
406 |
-
quantization_config=bnb_config_guard,
|
407 |
-
torch_dtype=torch.bfloat16,
|
408 |
-
device_map="auto",
|
409 |
-
)
|
410 |
-
|
411 |
-
def moderate_with_template(chat):
|
412 |
-
input_ids = guard_tokenizer.apply_chat_template(chat, return_tensors="pt")
|
413 |
-
output = guard_model.generate(input_ids=input_ids, max_new_tokens=100, pad_token_id=0)
|
414 |
-
prompt_len = input_ids.shape[-1]
|
415 |
-
return guard_tokenizer.decode(output[0][prompt_len:], skip_special_tokens=True)
|
416 |
-
|
417 |
-
def invoking(question):
|
418 |
-
return query_rag_chain.invoke(question)
|
419 |
-
|
420 |
-
def answer_question(question):
|
421 |
-
|
422 |
-
# Check if the question is safe using Llama guard
|
423 |
-
chat = [ {"role": "user", "content": question} ]
|
424 |
-
|
425 |
-
if not moderate_with_template(chat) == 'safe':
|
426 |
-
return "I'm sorry, but I can't respond to that question as it may contain inappropriate content."
|
427 |
-
|
428 |
-
ai_msg = invoking(question) # Generate AI response
|
429 |
-
|
430 |
-
|
431 |
-
system_response = [
|
432 |
-
{"role": "user", "content": question},
|
433 |
-
{"role": "assistant", "content": ai_msg},
|
434 |
-
]
|
435 |
-
if not moderate_with_template(system_response) == 'safe':
|
436 |
-
return "I generated a response, but it may contain inappropriate content. Let me try again with a more appropriate answer."
|
437 |
-
else:
|
438 |
-
return ai_msg
|
439 |
-
|
440 |
-
# answer_question("how to kill everybody")
|
441 |
-
|
442 |
-
"""# 🤖 *AI* assistent"""
|
443 |
-
|
444 |
-
|
445 |
-
# Commented out IPython magic to ensure Python compatibility.
|
446 |
-
!update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.8 2
|
447 |
-
!update-alternatives --install /usr/local/bin/python3 python3 /usr/bin/python3.9 1
|
448 |
-
!sudo apt install python3.8
|
449 |
-
|
450 |
-
!sudo apt-get install python3.8-distutils
|
451 |
-
|
452 |
-
!python --version
|
453 |
-
|
454 |
-
!apt-get update
|
455 |
-
|
456 |
-
!apt install software-properties-common
|
457 |
-
|
458 |
-
!sudo dpkg --remove --force-remove-reinstreq python3-pip python3-setuptools python3-wheel
|
459 |
-
|
460 |
-
!apt-get install python3-pip
|
461 |
-
|
462 |
-
print('Git clone project and install requirements...')
|
463 |
-
!git clone https://github.com/Winfredy/SadTalker &> /dev/null
|
464 |
-
# %cd SadTalker
|
465 |
-
!export PYTHONPATH=/content/SadTalker:$PYTHONPATH
|
466 |
-
!python3.8 -m pip install torch==1.12.1+cu113 torchvision==0.13.1+cu113 torchaudio==0.12.1 --extra-index-url https://download.pytorch.org/whl/cu113
|
467 |
-
!apt update
|
468 |
-
!apt install ffmpeg &> /dev/null
|
469 |
-
!python3.8 -m pip install -r requirements.txt
|
470 |
-
|
471 |
-
print('Download pre-trained models...')
|
472 |
-
!rm -rf checkpoints
|
473 |
-
!bash scripts/download_models.sh
|
474 |
-
|
475 |
-
"""# ⛳ 3D Shape"""
|
476 |
-
|
477 |
-
# Commented out IPython magic to ensure Python compatibility.
|
478 |
-
!git clone https://github.com/openai/shap-e
|
479 |
-
# %cd shap-e
|
480 |
-
|
481 |
-
|
482 |
-
import torch
|
483 |
-
from shap_e.diffusion.sample import sample_latents
|
484 |
-
from shap_e.diffusion.gaussian_diffusion import diffusion_from_config
|
485 |
-
from shap_e.models.download import load_model, load_config
|
486 |
-
from shap_e.util.notebooks import create_pan_cameras, decode_latent_images, gif_widget
|
487 |
-
|
488 |
-
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
489 |
-
|
490 |
-
import imageio
|
491 |
-
import os
|
492 |
-
import hashlib
|
493 |
-
|
494 |
-
def generate_gif(prompt):
|
495 |
-
# device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
|
496 |
-
|
497 |
-
# Load models and diffusion configuration
|
498 |
-
xm = load_model('transmitter', device=device)
|
499 |
-
model = load_model('text300M', device=device)
|
500 |
-
diffusion = diffusion_from_config(load_config('diffusion'))
|
501 |
-
|
502 |
-
# Generate latents
|
503 |
-
batch_size = 1
|
504 |
-
guidance_scale = 8.95
|
505 |
-
render_mode = 'nerf'
|
506 |
-
size = 128
|
507 |
-
|
508 |
-
latents = sample_latents(
|
509 |
-
batch_size=batch_size,
|
510 |
-
model=model,
|
511 |
-
diffusion=diffusion,
|
512 |
-
guidance_scale=guidance_scale,
|
513 |
-
model_kwargs=dict(texts=[prompt] * batch_size),
|
514 |
-
progress=True,
|
515 |
-
clip_denoised=True,
|
516 |
-
use_fp16=True,
|
517 |
-
use_karras=True,
|
518 |
-
karras_steps=64,
|
519 |
-
sigma_min=1e-3,
|
520 |
-
sigma_max=160,
|
521 |
-
s_churn=0,
|
522 |
-
)
|
523 |
-
|
524 |
-
# Create cameras
|
525 |
-
cameras = create_pan_cameras(size, device)
|
526 |
-
|
527 |
-
# Render images and create GIF
|
528 |
-
for i, latent in enumerate(latents):
|
529 |
-
images = decode_latent_images(xm, latent, cameras, rendering_mode=render_mode)
|
530 |
-
|
531 |
-
# Ensure the directory exists
|
532 |
-
gif_dir = "generated_gifs"
|
533 |
-
os.makedirs(gif_dir, exist_ok=True)
|
534 |
-
|
535 |
-
# Generate a short, unique file name using a hash of the prompt
|
536 |
-
prompt_hash = hashlib.md5(prompt.encode()).hexdigest()[:10]
|
537 |
-
gif_path = os.path.join(gif_dir, f"{prompt_hash}.gif")
|
538 |
-
|
539 |
-
# Save the images as a GIF
|
540 |
-
imageio.mimsave(gif_path, images, fps=10) # Save images as GIF
|
541 |
-
|
542 |
-
return gif_path
|
543 |
-
|
544 |
-
|
545 |
-
|
546 |
-
"""#big ⛏ func"""
|
547 |
-
|
548 |
-
import ipywidgets as widgets
|
549 |
-
import glob
|
550 |
-
import matplotlib.pyplot as plt
|
551 |
-
from IPython.display import display, HTML
|
552 |
-
from base64 import b64encode
|
553 |
-
import os
|
554 |
-
import sys
|
555 |
-
import subprocess
|
556 |
-
|
557 |
-
from google.colab import drive
|
558 |
-
drive.mount('/content/drive')
|
559 |
-
|
560 |
-
import os
|
561 |
-
import subprocess
|
562 |
-
import glob
|
563 |
-
|
564 |
-
def animate_image(audio_file):
|
565 |
-
# Display the selected image (optional if using in Gradio)
|
566 |
-
img_path = '/content/drive/MyDrive/img_9.png'
|
567 |
-
# print(f"Image Has Been Seleceted: ")
|
568 |
-
|
569 |
-
# Run the animation generation script
|
570 |
-
result = subprocess.run([
|
571 |
-
"python3.8", "inference.py", "--driven_audio", audio_file,
|
572 |
-
"--source_image", img_path, "--result_dir", "./results", "--still", "--preprocess", "full", "--enhancer", "gfpgan"
|
573 |
-
], capture_output=True, text=True)
|
574 |
-
|
575 |
-
# Check for errors
|
576 |
-
if result.stderr:
|
577 |
-
print("Errors:", result.stderr, file=sys.stderr)
|
578 |
-
|
579 |
-
# Find the generated video file
|
580 |
-
mp4_files = glob.glob('./results/*.mp4')
|
581 |
-
|
582 |
-
if mp4_files:
|
583 |
-
mp4_path = mp4_files[0]
|
584 |
-
print(f"Generated animation: {mp4_path}")
|
585 |
-
return mp4_path
|
586 |
-
else:
|
587 |
-
print("No results found.")
|
588 |
-
return None
|
589 |
-
|
590 |
-
"""# 🚀 Gradio"""
|
591 |
-
|
592 |
-
import gradio as gr
|
593 |
-
|
594 |
-
with gr.Blocks() as demo:
|
595 |
-
gr.Markdown("## Summarization and Animation Tool")
|
596 |
-
|
597 |
-
with gr.Row():
|
598 |
-
with gr.Column():
|
599 |
-
input_file = gr.File(label="Upload File", type='filepath')
|
600 |
-
summary = gr.Textbox(label="Summary", lines=3)
|
601 |
-
# evaluation_summary = gr.Textbox(label="Evaluation Summary", lines=3)
|
602 |
-
animation_video = gr.Video(label="Animation Video")
|
603 |
-
shape = gr.Image(label="3D Shape GIF")
|
604 |
-
question = gr.Textbox(label="Question", lines=3)
|
605 |
-
answer = gr.Textbox(label="Answer", lines=3)
|
606 |
-
|
607 |
-
|
608 |
-
summarize_button = gr.Button("Summarize")
|
609 |
-
summarize_button.click(process_question, inputs=input_file, outputs=[summary,animation_video,shape])
|
610 |
-
|
611 |
-
|
612 |
-
question_button = gr.Button("Ask Question")
|
613 |
-
question_button.click(lambda q: answer_question(q.strip()), inputs=[question], outputs=[answer])
|
614 |
-
|
615 |
-
demo.launch(debug=True)
|
616 |
-
|
617 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import gradio as gr
|
2 |
+
import os
|
3 |
+
from langchain_community.document_loaders import PyPDFLoader
|
4 |
from transformers import BitsAndBytesConfig, pipeline
|
|
|
5 |
from langchain_core.prompts import ChatPromptTemplate
|
6 |
from langchain_core.output_parsers import StrOutputParser
|
7 |
+
from io import BytesIO
|
8 |
+
import time
|
9 |
|
10 |
+
# Make sure to set the environment variables or load them from a .env file
|
11 |
+
os.environ['TOGETHER_API_KEY'] = 'your_together_api_key'
|
12 |
+
os.environ['PINECONE_API_KEY'] = 'your_pinecone_api_key'
|
13 |
+
ELEVENLABS_API_KEY = 'your_elevenlabs_api_key'
|
14 |
|
15 |
+
# Define the summarization chain
|
16 |
+
summary_prompt = """
|
17 |
+
You are an expert AI summarization model tasked with creating a comprehensive summary for 10 years old kids of the provided context. The summary should be approximately one page long and well-structured.
|
18 |
|
19 |
this is the context:
|
20 |
```{context}```
|
|
|
33 |
### Conclusion
|
34 |
- Suggest any potential actions, solutions, or recommendations.
|
35 |
|
|
|
|
|
36 |
this is the summary:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
"""
|
38 |
+
summary_prompt_template = ChatPromptTemplate.from_template(summary_prompt)
|
39 |
|
40 |
+
# Define the PDF extraction function
|
|
|
|
|
41 |
def extract_text_from_pdf(file):
|
42 |
loader = PyPDFLoader(file)
|
43 |
pages = loader.load_and_split()
|
44 |
+
pc.from_documents(pages, index_name='learnverse', embedding=em)
|
45 |
+
|
46 |
text = ""
|
47 |
for page in pages:
|
48 |
+
text += page.page_content
|
|
|
49 |
return text
|
50 |
|
51 |
+
# Define the text-to-speech function
|
52 |
+
def text_to_speech_stream(text):
|
53 |
+
client = ElevenLabs(api_key=ELEVENLABS_API_KEY)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
response = client.text_to_speech.convert(
|
55 |
voice_id="jBpfuIE2acCO8z3wKNLl",
|
56 |
optimize_streaming_latency="0",
|
|
|
71 |
audio_data.write(chunk)
|
72 |
|
73 |
audio_data.seek(0)
|
|
|
|
|
74 |
if not os.path.exists('samples'):
|
75 |
os.makedirs('samples')
|
76 |
|
|
|
77 |
with open('samples/output.mp3', 'wb') as f:
|
78 |
f.write(audio_data.read())
|
79 |
|
80 |
return 'samples/output.mp3'
|
81 |
|
82 |
+
# Define the evaluation function
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
83 |
def evaluate_summary(generated_summary):
|
84 |
+
wandb.init(project="learnverse")
|
85 |
+
|
86 |
+
reference_summaries = ["Reference summary 1...", "Reference summary 2...", "Reference summary 3..."]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
87 |
rouge = Rouge()
|
88 |
+
|
89 |
+
rouge_1, rouge_2, rouge_l = {'r': 0, 'p': 0, 'f': 0}, {'r': 0, 'p': 0, 'f': 0}, {'r': 0, 'p': 0, 'f': 0}
|
90 |
+
|
|
|
|
|
|
|
|
|
|
|
91 |
for reference in reference_summaries:
|
92 |
scores = rouge.get_scores(generated_summary, reference)
|
|
|
|
|
93 |
rouge_1['r'] += scores[0]['rouge-1']['r']
|
94 |
rouge_1['p'] += scores[0]['rouge-1']['p']
|
95 |
rouge_1['f'] += scores[0]['rouge-1']['f']
|
|
|
96 |
rouge_2['r'] += scores[0]['rouge-2']['r']
|
97 |
rouge_2['p'] += scores[0]['rouge-2']['p']
|
98 |
rouge_2['f'] += scores[0]['rouge-2']['f']
|
|
|
99 |
rouge_l['r'] += scores[0]['rouge-l']['r']
|
100 |
rouge_l['p'] += scores[0]['rouge-l']['p']
|
101 |
rouge_l['f'] += scores[0]['rouge-l']['f']
|
102 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
103 |
num_references = len(reference_summaries)
|
104 |
rouge_1 = {key: value / num_references for key, value in rouge_1.items()}
|
105 |
rouge_2 = {key: value / num_references for key, value in rouge_2.items()}
|
106 |
rouge_l = {key: value / num_references for key, value in rouge_l.items()}
|
107 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
108 |
wandb.log(rouge_1)
|
109 |
wandb.log(rouge_2)
|
110 |
wandb.log(rouge_l)
|
|
|
|
|
|
|
|
|
|
|
111 |
wandb.finish()
|
112 |
+
|
113 |
+
return {'ROUGE-1': rouge_1, 'ROUGE-2': rouge_2, 'ROUGE-L': rouge_l}
|
|
|
|
|
|
|
|
|
|
|
114 |
|
115 |
+
# Define the main processing function
|
116 |
def process_question(file):
|
|
|
|
|
|
|
|
|
|
|
117 |
pdffile = extract_text_from_pdf(file)
|
118 |
three_topics = topic_chain.invoke({"context": pdffile})
|
|
|
|
|
|
|
119 |
summary = summary_pdf_chain.invoke(pdffile)
|
|
|
|
|
|
|
|
|
120 |
evaluation = evaluate_summary(summary)
|
|
|
|
|
|
|
|
|
121 |
audio_file = text_to_speech_stream(summary)
|
122 |
+
return summary, evaluation, audio_file
|
123 |
+
|
124 |
+
# Define the Gradio interface
|
125 |
+
def gradio_interface(file):
|
126 |
+
summary, evaluation, audio_file = process_question(file)
|
127 |
+
return summary, evaluation, audio_file
|
128 |
+
|
129 |
+
# Launch the Gradio app
|
130 |
+
gr.Interface(
|
131 |
+
fn=gradio_interface,
|
132 |
+
inputs=gr.File(type="file", label="Upload PDF"),
|
133 |
+
outputs=[gr.Textbox(label="Summary"), gr.Textbox(label="Evaluation"), gr.Audio(label="Generated Audio")]
|
134 |
+
).launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
135 |
|