Spaces:
Sleeping
Sleeping
Commit
·
94f1ca3
1
Parent(s):
0af17d3
App Upload
Browse files- app.py +154 -0
- requirements.txt +8 -0
app.py
ADDED
@@ -0,0 +1,154 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# AUTOGENERATED! DO NOT EDIT! File to edit: ../drive/MyDrive/Codici/Python/Apps/Gradio_App/SemanticSearch_QA-v2.1.ipynb.
|
2 |
+
|
3 |
+
# %% auto 0
|
4 |
+
__all__ = ['model_name', 'qa_model', 'contexts', 'question', 'df_results', 'question_1', 'question_2', 'question_3', 'question_4',
|
5 |
+
'question_5', 'question_6', 'question_7', 'question_8', 'question_9', 'question_10', 'title', 'description',
|
6 |
+
'data', 'context_df', 'question_input', 'contexts_input', 'n_answers_input', 'full_context_input',
|
7 |
+
'confidence_threshold_input', 'intf', 'get_answers']
|
8 |
+
|
9 |
+
# %% ../drive/MyDrive/Codici/Python/Apps/Gradio_App/SemanticSearch_QA-v2.1.ipynb 2
|
10 |
+
import pandas as pd
|
11 |
+
import gradio as gr
|
12 |
+
from transformers import AutoModelForQuestionAnswering, AutoTokenizer, pipeline
|
13 |
+
|
14 |
+
model_name = 'Francesco-A/bert-finetuned-squad-v1'
|
15 |
+
# model_name = "deepset/roberta-base-squad2"
|
16 |
+
|
17 |
+
qa_model = pipeline(task = 'question-answering',
|
18 |
+
model = model_name,
|
19 |
+
tokenizer = model_name)
|
20 |
+
|
21 |
+
# %% ../drive/MyDrive/Codici/Python/Apps/Gradio_App/SemanticSearch_QA-v2.1.ipynb 5
|
22 |
+
def get_answers(question, contexts, n_answers=1, full_context=True, confidence_threshold = 0.5):
|
23 |
+
results = []
|
24 |
+
|
25 |
+
if isinstance(contexts, pd.DataFrame):
|
26 |
+
# If it's a DataFrame, get the values from the 'Context' column as a list
|
27 |
+
contexts = contexts['Context'].to_list()
|
28 |
+
|
29 |
+
|
30 |
+
for i, context in enumerate(contexts):
|
31 |
+
QA_input = {'question': question, 'context': context}
|
32 |
+
res = qa_model(QA_input)
|
33 |
+
|
34 |
+
results_dict = {
|
35 |
+
'context_idx': i,
|
36 |
+
# 'Question': question,
|
37 |
+
'Answer': res['answer'],
|
38 |
+
'Score': round(res['score'],3)
|
39 |
+
}
|
40 |
+
|
41 |
+
if full_context:
|
42 |
+
results_dict['Full Context'] = context
|
43 |
+
|
44 |
+
results.append(results_dict)
|
45 |
+
|
46 |
+
df = pd.DataFrame(results)
|
47 |
+
df = df[df['Score'] >= confidence_threshold]
|
48 |
+
df = df.sort_values(by='Score', ascending=False).head(n_answers)
|
49 |
+
df = df.reset_index(drop=True) # Reset index after sorting
|
50 |
+
|
51 |
+
return df
|
52 |
+
|
53 |
+
# Example usage:
|
54 |
+
contexts = [
|
55 |
+
'The option to convert models between FARM and transformers gives freedom to the user and let people easily switch between frameworks.',
|
56 |
+
'Model conversion enables interoperability between different NLP libraries.',
|
57 |
+
'Converting models allows for leveraging the strengths of various tools.'
|
58 |
+
]
|
59 |
+
|
60 |
+
question = "Why is model conversion important?"
|
61 |
+
|
62 |
+
df_results = get_answers(question,contexts,n_answers=2,full_context=False, confidence_threshold = 0.25)
|
63 |
+
df_results
|
64 |
+
|
65 |
+
# %% ../drive/MyDrive/Codici/Python/Apps/Gradio_App/SemanticSearch_QA-v2.1.ipynb 6
|
66 |
+
# Define example question(s)
|
67 |
+
question_1 = "What are the main features of the new XPhone 20?"
|
68 |
+
question_2 = "What are some benefits of regular exercise?"
|
69 |
+
question_3 = "What is the color of a rose?"
|
70 |
+
question_4 = "How does photosynthesis work in plants?"
|
71 |
+
question_5 = "At what temperature does water boil?"
|
72 |
+
question_6 = "Where can I find potassium?"
|
73 |
+
question_7 = "How does the internet function?"
|
74 |
+
question_8 = "What are the ingredients for making a classic margarita?"
|
75 |
+
question_9 = "How does cellular respiration work?"
|
76 |
+
question_10 = "Is money important?"
|
77 |
+
|
78 |
+
# Define example contexts as a list of strings
|
79 |
+
contexts = [
|
80 |
+
"The XPhone 20 is expected to come with an improved camera system, featuring advanced image stabilization and enhanced low-light capabilities.",
|
81 |
+
"Regular exercise has been shown to reduce the risk of chronic diseases such as heart disease, diabetes, and certain types of cancer.",
|
82 |
+
"Roses come in various colors, including red, pink, yellow, white, and even blue (though blue roses are rare and often created through genetic modification).",
|
83 |
+
"Photosynthesis occurs in the chloroplasts of plant cells, where chlorophyll captures sunlight and converts it into chemical energy.",
|
84 |
+
"Water boils at different temperatures depending on factors like altitude and atmospheric pressure. At sea level, it boils at 100 degrees Celsius or 212 degrees Fahrenheit.",
|
85 |
+
"Potassium is an essential mineral that can be found in various foods such as bananas, potatoes, spinach, and oranges.",
|
86 |
+
"The internet functions through a complex system of data transmission protocols, routers, and servers that allow for the exchange of information globally.",
|
87 |
+
"A classic margarita typically consists of tequila, lime juice, triple sec (or orange liqueur), and is often served with a salted rim.",
|
88 |
+
"Cellular respiration takes place in the mitochondria of cells, where glucose and oxygen are converted into ATP (adenosine triphosphate) and carbon dioxide.",
|
89 |
+
"Money is a medium of exchange that facilitates transactions of goods and services. Its importance lies in its role in economic systems and the ability to represent value.",
|
90 |
+
"The XPhone 20 may feature an OLED display for vibrant colors and deep blacks, providing a high-quality visual experience.",
|
91 |
+
"Exercise releases endorphins, which are chemicals in the brain that help improve mood and reduce feelings of stress and anxiety.",
|
92 |
+
"Different species of roses can have variations in color, including shades of red, pink, yellow, and white.",
|
93 |
+
"During photosynthesis, plants also release oxygen as a byproduct, which is essential for the survival of many organisms on Earth.",
|
94 |
+
"Water boils at a lower temperature at higher altitudes due to the reduced atmospheric pressure. For example, in the mountains, it may boil below 100 degrees Celsius.",
|
95 |
+
"Potassium is crucial for proper muscle function, nerve function, and maintaining fluid balance in the body.",
|
96 |
+
"The internet relies on a system of interconnected networks, including wired and wireless connections, to transmit data across the globe.",
|
97 |
+
"In addition to the core ingredients, a classic margarita can also be garnished with a wedge of lime for added flavor.",
|
98 |
+
"Cellular respiration involves several stages, including glycolysis, the Krebs cycle, and the electron transport chain, to extract energy from glucose.",
|
99 |
+
"Money serves as a unit of account, allowing for standardized pricing and valuation of goods and services in economies worldwide."
|
100 |
+
"The XPhone 20 is rumored to feature a smaller notch, providing more screen real estate for users. This allows for an immersive viewing experience.",
|
101 |
+
"Photosynthesis is the process by which plants convert carbon dioxide, water, and sunlight into glucose and oxygen.",
|
102 |
+
"Bananas are a great source of potassium.",
|
103 |
+
"The theory of relativity was developed by Albert Einstein and revolutionized our understanding of space and time.",
|
104 |
+
"The Eiffel Tower is located in Paris, France.",
|
105 |
+
"Reports suggest that the XPhone 20 will have significant improvements in battery life compared to its predecessor. Users can expect a longer-lasting device.",
|
106 |
+
"A penny saved is a penny earned.",
|
107 |
+
"Water boils at 100 degrees Celsius.",
|
108 |
+
"The Great Wall of China is one of the most impressive architectural feats in history.",
|
109 |
+
"The capital of Japan is Tokyo.",
|
110 |
+
"One of the anticipated features of the XPhone 20 is a faster and more powerful A16 chip. This will result in smoother and more efficient performance.",
|
111 |
+
"Roses are red, violets are blue.",
|
112 |
+
"Regular exercise can help improve cardiovascular health and strengthen muscles.",
|
113 |
+
"A classic margarita is made with tequila, lime juice, and orange liqueur.",
|
114 |
+
"Cellular respiration is the process by which cells convert glucose and oxygen into energy, carbon dioxide, and water.",
|
115 |
+
"The internet is a global network of interconnected computers and servers that allows the sharing of information and resources.",
|
116 |
+
"Mount Everest is the highest mountain in the world, located in the Himalayas.",
|
117 |
+
"The sun rises in the east and sets in the west.",
|
118 |
+
"The Mona Lisa is a famous portrait painting by Leonardo da Vinci.",
|
119 |
+
"The Declaration of Independence was adopted by the Continental Congress on July 4, 1776.",
|
120 |
+
]
|
121 |
+
|
122 |
+
# %% ../drive/MyDrive/Codici/Python/Apps/Gradio_App/SemanticSearch_QA-v2.1.ipynb 9
|
123 |
+
title = 'SemanticSearch_QA-v2'
|
124 |
+
description = """
|
125 |
+
QA model: [Francesco-A/bert-finetuned-squad-v1](https://huggingface.co/Francesco-A/bert-finetuned-squad-v1)
|
126 |
+
"""
|
127 |
+
|
128 |
+
data = {
|
129 |
+
'Context': contexts,
|
130 |
+
}
|
131 |
+
|
132 |
+
context_df = pd.DataFrame(data)
|
133 |
+
|
134 |
+
question_input = gr.Textbox(label="Question", placeholder="Enter your question here")
|
135 |
+
contexts_input = gr.Dataframe(value=context_df, headers=["Context"], interactive=True, type="pandas", label="Contexts")
|
136 |
+
n_answers_input = gr.Slider(minimum=1, maximum=10, step=1, value=1, label="Number of Answers")
|
137 |
+
full_context_input = gr.Checkbox(label="Include Full Context", value=True)
|
138 |
+
confidence_threshold_input = gr.Slider(minimum=0.0, maximum=1.0, step=0.1, value=0.5, label="Confidence Threshold")
|
139 |
+
|
140 |
+
intf = gr.Interface(fn=get_answers,
|
141 |
+
inputs= [question_input, contexts_input, n_answers_input,confidence_threshold_input],
|
142 |
+
outputs= gr.components.Dataframe(),
|
143 |
+
examples = [[question_1,context_df,3,False,0.3],
|
144 |
+
[question_2,context_df,5,True,0.5],
|
145 |
+
[question_4,context_df,10,False,0.1]],
|
146 |
+
|
147 |
+
title=title,
|
148 |
+
description=description,
|
149 |
+
# article=long_desc
|
150 |
+
)
|
151 |
+
|
152 |
+
intf.launch(inline=True,
|
153 |
+
# share=True
|
154 |
+
)
|
requirements.txt
ADDED
@@ -0,0 +1,8 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
gradio==5.7.1
|
2 |
+
gradio_client==1.5.0
|
3 |
+
geopandas==1.0.1
|
4 |
+
pandas==2.2.2
|
5 |
+
pandas-datareader==0.10.0
|
6 |
+
pandas-gbq==0.24.0
|
7 |
+
pandas-stubs==2.2.2.240909
|
8 |
+
sklearn-pandas==2.2.0
|