Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from sentence_transformers import SentenceTransformer
|
3 |
+
from scipy.spatial.distance import cosine
|
4 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
5 |
+
import nltk
|
6 |
+
|
7 |
+
# Carica il modello
|
8 |
+
model = SentenceTransformer('sentence-transformers/all-roberta-large-v1', device='cpu')
|
9 |
+
nltk.download('punkt')
|
10 |
+
|
11 |
+
# Preprocessamento manuale (potresti caricare il manuale da un file o base di dati)
|
12 |
+
with open('manual.txt', 'r', encoding='utf-8') as file:
|
13 |
+
text = file.read()
|
14 |
+
|
15 |
+
# Tokenizza il testo
|
16 |
+
sentences = nltk.sent_tokenize(text)
|
17 |
+
|
18 |
+
# Crea gli embedding per il manuale
|
19 |
+
embeddings = model.encode(sentences, batch_size=8, show_progress_bar=True)
|
20 |
+
|
21 |
+
# Funzione per ottenere le frasi più rilevanti
|
22 |
+
def find_relevant_sentences(query):
|
23 |
+
query_embedding = model.encode([query])
|
24 |
+
similarities = cosine_similarity(query_embedding, embeddings).flatten()
|
25 |
+
|
26 |
+
# Filtra i risultati in base alla similitudine
|
27 |
+
threshold = 0.5
|
28 |
+
filtered_results = [(idx, sim) for idx, sim in enumerate(similarities) if sim >= threshold]
|
29 |
+
|
30 |
+
# Ordina i risultati per similitudine
|
31 |
+
filtered_results.sort(key=lambda x: x[1], reverse=True)
|
32 |
+
|
33 |
+
# Ottieni le frasi più rilevanti
|
34 |
+
top_n = 4
|
35 |
+
relevant_sentences = [sentences[idx] for idx, _ in filtered_results[:top_n]]
|
36 |
+
|
37 |
+
return relevant_sentences
|
38 |
+
|
39 |
+
# Interfaccia Gradio
|
40 |
+
iface = gr.Interface(
|
41 |
+
fn=find_relevant_sentences,
|
42 |
+
inputs=gr.Textbox(label="Insert your query"),
|
43 |
+
outputs=gr.Textbox(label="Relevant sentences"),
|
44 |
+
title="Manual Querying System",
|
45 |
+
description="Enter a question about the machine, and this tool will find the most relevant sentences from the manual."
|
46 |
+
)
|
47 |
+
|
48 |
+
# Avvia l'app Gradio
|
49 |
+
iface.launch()
|