Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,5 +1,9 @@
|
|
|
|
|
|
|
|
1 |
import openai
|
2 |
import os
|
|
|
3 |
|
4 |
# Configura la tua chiave API in modo sicuro
|
5 |
api_key = os.getenv("OPENAI_API_KEY") # Imposta la chiave come variabile d'ambiente
|
@@ -8,12 +12,64 @@ if not api_key:
|
|
8 |
raise ValueError("Chiave API OpenAI non trovata. Assicurati di aver impostato OPENAI_API_KEY.")
|
9 |
|
10 |
# Crea il client utilizzando la chiave API
|
11 |
-
#openai.api_key = api_key # Usa direttamente api_key
|
12 |
-
|
13 |
client = openai.Client(api_key=api_key)
|
14 |
|
15 |
-
|
16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
17 |
def rispondi_a_domanda(domanda, testo, max_token_risposta=350):
|
18 |
try:
|
19 |
# Chiamata API di OpenAI
|
@@ -36,33 +92,33 @@ def rispondi_a_domanda(domanda, testo, max_token_risposta=350):
|
|
36 |
)
|
37 |
|
38 |
# Estrai la risposta
|
39 |
-
|
40 |
-
risposta_finale = risposta.choices[0].message.content
|
41 |
return risposta_finale
|
42 |
|
43 |
except Exception as e:
|
44 |
print(f"Si è verificato un errore: {e}")
|
45 |
-
return
|
46 |
-
|
47 |
-
#
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
|
62 |
-
|
63 |
-
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
|
|
|
68 |
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from langchain_community.vectorstores import FAISS
|
3 |
+
from langchain_community.embeddings import HuggingFaceEmbeddings
|
4 |
import openai
|
5 |
import os
|
6 |
+
import zipfile
|
7 |
|
8 |
# Configura la tua chiave API in modo sicuro
|
9 |
api_key = os.getenv("OPENAI_API_KEY") # Imposta la chiave come variabile d'ambiente
|
|
|
12 |
raise ValueError("Chiave API OpenAI non trovata. Assicurati di aver impostato OPENAI_API_KEY.")
|
13 |
|
14 |
# Crea il client utilizzando la chiave API
|
|
|
|
|
15 |
client = openai.Client(api_key=api_key)
|
16 |
|
17 |
+
# Percorsi per il primo file ZIP
|
18 |
+
zip_path_m = "faiss_manual_index.zip" # File ZIP per l'indice manuale
|
19 |
+
faiss_manual_index = "faiss_manual_index" # Sottocartella per estrazione manuale
|
20 |
+
|
21 |
+
# Controlla se la directory esiste già
|
22 |
+
if not os.path.exists(faiss_manual_index):
|
23 |
+
os.makedirs(faiss_manual_index) # Crea la directory
|
24 |
+
|
25 |
+
# Percorsi per il secondo file ZIP
|
26 |
+
zip_path_p = "faiss_problems_index.zip" # File ZIP per l'indice problemi
|
27 |
+
faiss_problems_index = "faiss_problems_index" # Sottocartella per estrazione problemi
|
28 |
+
|
29 |
+
# Controlla se la directory esiste già
|
30 |
+
if not os.path.exists(faiss_problems_index):
|
31 |
+
os.makedirs(faiss_problems_index) # Crea la directory
|
32 |
+
|
33 |
+
# Estrai il primo file ZIP se non esiste già
|
34 |
+
if os.path.exists(zip_path_m): # Controlla che il file zip esista
|
35 |
+
with zipfile.ZipFile(zip_path_m, 'r') as zip_ref:
|
36 |
+
zip_ref.extractall(faiss_manual_index)
|
37 |
+
print(f"Files estratti nella directory: {faiss_manual_index}")
|
38 |
+
else:
|
39 |
+
print(f"File {zip_path_m} non trovato. Assicurati di caricarlo nello Space.")
|
40 |
+
|
41 |
+
# Estrai il secondo file ZIP se non esiste già
|
42 |
+
if os.path.exists(zip_path_p): # Controlla che il file zip esista
|
43 |
+
with zipfile.ZipFile(zip_path_p, 'r') as zip_ref:
|
44 |
+
zip_ref.extractall(faiss_problems_index)
|
45 |
+
print(f"Files estratti nella directory: {faiss_problems_index}")
|
46 |
+
else:
|
47 |
+
print(f"File {zip_path_p} non trovato. Assicurati di caricarlo nello Space.")
|
48 |
+
|
49 |
+
# Carica il modello di embedding
|
50 |
+
embedding_model = HuggingFaceEmbeddings(model_name="sentence-transformers/LaBSE")
|
51 |
+
|
52 |
+
# Carica i vectorstore FAISS salvati
|
53 |
+
manual_vectorstore = FAISS.load_local(faiss_manual_index, embedding_model, allow_dangerous_deserialization=True)
|
54 |
+
problems_vectorstore = FAISS.load_local(faiss_problems_index, embedding_model, allow_dangerous_deserialization=True)
|
55 |
+
|
56 |
+
# Funzione per cercare nei dati FAISS e interrogare GPT
|
57 |
+
def search_and_answer(query):
|
58 |
+
# Cerca nei manuali
|
59 |
+
manual_results = manual_vectorstore.similarity_search(query, k=2)
|
60 |
+
manual_output = "\n\n".join([doc.page_content for doc in manual_results])
|
61 |
+
|
62 |
+
# Cerca nei problemi
|
63 |
+
problems_results = problems_vectorstore.similarity_search(query, k=2)
|
64 |
+
problems_output = "\n\n".join([doc.page_content for doc in problems_results])
|
65 |
+
|
66 |
+
# Costruisce una domanda combinata
|
67 |
+
combined_text = f"Manual Results: {manual_output}\n\nProblems Results: {problems_output}"
|
68 |
+
response = rispondi_a_domanda(query, combined_text)
|
69 |
+
|
70 |
+
return manual_output, problems_output, response
|
71 |
+
|
72 |
+
# Funzione per interrogare GPT
|
73 |
def rispondi_a_domanda(domanda, testo, max_token_risposta=350):
|
74 |
try:
|
75 |
# Chiamata API di OpenAI
|
|
|
92 |
)
|
93 |
|
94 |
# Estrai la risposta
|
95 |
+
risposta_finale = risposta['choices'][0]['message']['content']
|
|
|
96 |
return risposta_finale
|
97 |
|
98 |
except Exception as e:
|
99 |
print(f"Si è verificato un errore: {e}")
|
100 |
+
return "Errore nell'elaborazione della risposta."
|
101 |
+
|
102 |
+
# Interfaccia Gradio
|
103 |
+
examples = [
|
104 |
+
["How to change the knife?"],
|
105 |
+
["What are the safety precautions for using the machine?"],
|
106 |
+
["How can I get help with the machine?"]
|
107 |
+
]
|
108 |
+
|
109 |
+
iface = gr.Interface(
|
110 |
+
fn=search_and_answer,
|
111 |
+
inputs=gr.Textbox(lines=2, placeholder="Enter your question here..."),
|
112 |
+
outputs=[
|
113 |
+
gr.Textbox(label="Manual Results"),
|
114 |
+
gr.Textbox(label="Issues Results"),
|
115 |
+
gr.Textbox(label="GPT-Generated Answer")
|
116 |
+
],
|
117 |
+
examples=examples,
|
118 |
+
title="Manual Querying System with GPT",
|
119 |
+
description="Enter a question to get relevant information extracted from the manual and related issues, followed by a GPT-generated answer."
|
120 |
+
)
|
121 |
+
|
122 |
+
# Avvia l'app
|
123 |
+
iface.launch()
|
124 |
|