Mauro24 commited on
Commit
0cea8e5
·
verified ·
1 Parent(s): a0e6e11

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +30 -143
app.py CHANGED
@@ -1,159 +1,46 @@
1
 
2
- import os
3
- import spacy
4
  import gradio as gr
5
- from sentence_transformers import SentenceTransformer
6
- from sklearn.metrics.pairwise import cosine_similarity
7
- import numpy as np
8
- import zipfile
9
- import re
10
 
11
- print("Directory corrente:", os.getcwd())
 
12
 
13
- zip_path = "en_core_web_lg-3.8.0.zip" # Carica il file ZIP nella cartella del progetto
14
- extraction_dir = "./extracted_models" # Scegli una sottocartella per l'estrazione
15
- test_dir = "./extracted_models/en_core_web_lg-3.8.0" # Cartella dopo l'estrazione
 
16
 
17
- # Verifica se la cartella esiste già
18
- if not os.path.exists(test_dir):
19
- # Se la cartella non esiste, decomprimi il file ZIP
20
- with zipfile.ZipFile(zip_path, 'r') as zip_ref:
21
- zip_ref.extractall(extraction_dir)
22
- print(f"Modello estratto correttamente nella cartella {extraction_dir}")
23
 
24
- # Percorso del file zip caricato
25
- zip_path = "images.zip" # Assicurati che il file sia stato caricato su Hugging Face
26
- extract_to = "images" # Directory di destinazione per le immagini
27
 
28
- # Controlla se la directory esiste già
29
- if not os.path.exists(extract_to):
30
- os.makedirs(extract_to) # Crea la directory
31
-
32
- # Estrai il file zip
33
- if os.path.exists(zip_path): # Controlla che il file zip esista
34
- with zipfile.ZipFile(zip_path, 'r') as zip_ref:
35
- zip_ref.extractall(extract_to)
36
- print(f"Immagini estratte nella directory: {extract_to}")
37
- print("Contenuto della directory images:", os.listdir(extract_to))
38
- else:
39
- print(f"File {zip_path} non trovato. Assicurati di caricarlo nello Space.")
40
-
41
-
42
-
43
- # Percorso della cartella estratta
44
- model_path = os.path.join(extraction_dir, "en_core_web_lg-3.8.0") # Assicurati che sia corretto
45
-
46
- # Carica il modello
47
- nlp = spacy.load(model_path)
48
-
49
-
50
- # Carica il modello SentenceTransformer
51
-
52
- model = SentenceTransformer('sentence-transformers/paraphrase-multilingual-mpnet-base-v2', device='cpu')
53
-
54
-
55
-
56
-
57
- # Preprocessamento manuale (carica il manuale da un file o base di dati)
58
- with open('testo.txt', 'r', encoding='utf-8') as file:
59
- text = file.read()
60
-
61
- # Tokenizza il testo in frasi usando SpaCy
62
- doc = nlp(text)
63
- sentences = [sent.text for sent in doc.sents] # Estrarre frasi dal testo
64
-
65
- # Crea gli embedding per il manuale
66
- embeddings = model.encode(sentences, batch_size=8, show_progress_bar=True)
67
-
68
- # Percorso della cartella delle immagini
69
- image_folder = "images"
70
-
71
- def extract_figure_numbers(text):
72
- """Estrae tutti i numeri delle figure da una frase."""
73
- matches = re.findall(r"\(Figure (\d+)\)", text, re.IGNORECASE)
74
- if matches:
75
- return matches # Restituisce una lista di numeri di figure
76
- return []
77
-
78
-
79
- def generate_figure_mapping(folder):
80
- """Genera la mappatura delle figure dal nome dei file immagini."""
81
- mapping = {}
82
- for file_name in os.listdir(folder):
83
- if file_name.lower().endswith((".jpg", ".png", ".jpeg")):
84
- figure_reference = file_name.split(".")[0].replace("_", " ")
85
- mapping[figure_reference] = file_name
86
- return mapping
87
-
88
- figure_mapping = generate_figure_mapping(image_folder)
89
- #print("Generated figure mapping:", figure_mapping)
90
-
91
- def format_sentences(sentences):
92
- """
93
- Converte la lista in una stringa, sostituendo i delimitatori '|' con un a capo senza aggiungere spazi extra.
94
- Interrompe il processo se trova '.end'.
95
- """
96
- # Uniamo la lista in una singola stringa
97
- sentences_str = " ".join(sentences)
98
-
99
- # Interrompiamo al primo '.end'
100
- if ".end" in sentences_str:
101
- sentences_str = sentences_str.split(".end")[0]
102
 
103
- # Sostituiamo il delimitatore '|' con un a capo
104
- formatted_response = sentences_str.replace(" |", "\n").replace("|", "\n")
105
-
106
- return formatted_response
107
-
108
- def find_relevant_sentences(query, threshold=0.2, top_n=6):
109
- """Trova le frasi più rilevanti e le immagini collegate."""
110
- global sentences
111
- query_embedding = model.encode([query])
112
- similarities = cosine_similarity(query_embedding, embeddings).flatten()
113
-
114
- filtered_results = [(idx, sim) for idx, sim in enumerate(similarities) if sim >= threshold]
115
- filtered_results.sort(key=lambda x: x[1], reverse=True)
116
-
117
- if not filtered_results:
118
- return "**RESPONSE:**\nNo relevant sentences found for your query.", None
119
-
120
- relevant_sentences = [sentences[idx] for idx, _ in filtered_results[:top_n]]
121
- relevant_images = set() # Usa un set per evitare duplicati
122
-
123
- for sent in relevant_sentences:
124
- figure_numbers = extract_figure_numbers(sent) # Restituisce una lista di figure
125
- for figure_number in figure_numbers:
126
- if figure_number in figure_mapping:
127
- image_path = os.path.join(image_folder, figure_mapping[figure_number])
128
- if os.path.exists(image_path):
129
- relevant_images.add(image_path) # Aggiunge al set
130
-
131
- # Formatta le frasi senza categorizzazione
132
- formatted_response = "****\n" + format_sentences(relevant_sentences)
133
- return formatted_response, list(relevant_images) # Converte il set in lista
134
-
135
-
136
-
137
- # Interfaccia Gradio
138
  examples = [
139
- ["irresponsible use of the machine?"],
140
- ["If I have a problem how can I get help?"],
141
- ["precautions when using the cutting machine"],
142
- ["How do I DRILL BIT REPLACEMENT ?"],
143
- ["instructions for changing the knife"],
144
- ["lubrication for the knife holder cylinder"]
145
  ]
146
 
 
147
  iface = gr.Interface(
148
- fn=find_relevant_sentences,
149
- inputs=gr.Textbox(label="Insert your query"),
150
  outputs=[
151
- gr.Textbox(label="Relevant sentences"),
152
- gr.Gallery(label="Relevant figures", value=[os.path.join(image_folder, "4b.jpg")]) # Anteprima immagine iniziale
153
- ],
154
- examples=examples,
155
- title="Manual Querying System",
156
- description="Enter a question about the machine, and this tool will find the most relevant sentences and associated figures from the manual.",
157
  )
158
 
 
159
  iface.launch()
 
1
 
 
 
2
  import gradio as gr
3
+ from langchain.vectorstores import FAISS
4
+ from langchain.embeddings import HuggingFaceEmbeddings
 
 
 
5
 
6
+ # Carica il modello di embedding
7
+ embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/LaBSE")
8
 
9
+ # Carica i vectorstore FAISS salvati
10
+ vectorstore = FAISS.load_local("faiss_index", embedding_model, allow_dangerous_deserialization=True)
11
+ manual_vectorstore = FAISS.load_local("faiss_manual_index", embedding_model, allow_dangerous_deserialization=True)
12
+ problems_vectorstore = FAISS.load_local("faiss_problems_index", embedding_model, allow_dangerous_deserialization=True)
13
 
14
+ def search_query(query):
15
+ # Cerca nei manuali
16
+ manual_results = manual_vectorstore.similarity_search(query, k=2)
17
+ manual_output = "\n\n".join([doc.page_content for doc in manual_results])
 
 
18
 
19
+ # Cerca nei problemi
20
+ problems_results = problems_vectorstore.similarity_search(query, k=2)
21
+ problems_output = "\n\n".join([doc.page_content for doc in problems_results])
22
 
23
+ # Restituisce i risultati come output diviso
24
+ return manual_output, problems_output
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
25
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
26
  examples = [
27
+ ["How to change the knife?"],
28
+ ["What are the safety precautions for using the machine?"],
29
+ ["How can I get help with the machine?"]
 
 
 
30
  ]
31
 
32
+ # Interfaccia Gradio
33
  iface = gr.Interface(
34
+ fn=search_query,
35
+ inputs=gr.Textbox(lines=2, placeholder="Enter your question here..."),
36
  outputs=[
37
+ gr.Textbox(label="Manual Results"),
38
+ gr.Textbox(label="Issues Results")
39
+ ],
40
+ examples=examples,
41
+ title="Manual Querying System",
42
+ description="Enter a question to get relevant information extracted from the manual and the most common related issues."
43
  )
44
 
45
+ # Avvia l'app
46
  iface.launch()