GattoNero commited on
Commit
ec894d6
·
verified ·
1 Parent(s): f16d61b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +80 -71
app.py CHANGED
@@ -22,7 +22,7 @@ logging.getLogger().setLevel(logging.DEBUG) # imposta il livello di log a DEBUG
22
 
23
  class BasicAgent:
24
  def __init__(self):
25
- print("Initializing LlamaIndex-based agent...")
26
 
27
  # Leggi la chiave OpenAI dall'ambiente
28
  openai_api_key = os.getenv("OPENAI_API_KEY")
@@ -49,8 +49,8 @@ class BasicAgent:
49
 
50
  # Prepara il query engine
51
  self.query_engine = self.index.as_query_engine()
52
- print("Agent ready.")
53
-
54
  def __call__(self, question: str) -> str:
55
  print(f"Received question: {question[:50]}...")
56
  response = self.query_engine.query(question)
@@ -62,85 +62,94 @@ class BasicAgent:
62
  return str(response)
63
  '''
64
 
65
- def __call__(self, question: str, context=None) -> str:
66
- if isinstance(context, str):
67
- #prompt = f"{context}\n\nDomanda: {question}"
68
- response = self.query_engine.query(question)
69
- # Stampa ragionamento interno
70
- print("Query response object:", response)
71
- print("Response text:", str(response))
72
- return response.text
73
-
74
- elif context and hasattr(context, "read"): # file immagine o audio
75
- file_bytes = context.read()
76
- filename = context.name
77
-
78
- if filename.endswith((".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif")):
79
- print("coso entrato in video file:", filename)
80
- image = Image.open(io.BytesIO(file_bytes))
81
- response = self.query_engine.query(
82
- messages=[
83
- {"role": "user", "content": [
84
- {"type": "text", "text": question},
85
- {"type": "image_url", "image_url": image}
86
- ]}
87
- ]
88
- )
89
- return response.choices[0].message.content
90
-
91
- elif filename.endswith((".mp3", ".wav", ".ogg")):
92
- print("coso entrato in audio file:", filename)
93
- response = self.query_engine.query(
94
- messages=[
95
- {"role": "user", "content": [
96
- {"type": "text", "text": question},
97
- {"type": "audio_url", "audio_url": file_bytes}
98
- ]}
99
- ]
100
- )
101
- return response.choices[0].message.content
102
-
103
- else:
104
- print("coso entrato in else")
105
- response = self.llm.complete(question)
106
- return response.text
107
 
108
-
 
109
 
110
- def answer_with_media(question, uploaded_file):
111
- file_content = ""
112
- file_path = None
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
113
 
114
- if uploaded_file is not None:
115
- file_path = Path(uploaded_file.name)
116
- suffix = file_path.suffix.lower()
 
117
 
118
- if suffix in [".txt", ".md", ".csv"]:
119
- with open(file_path, "r", encoding="utf-8") as f:
120
- file_content = f.read()
121
- elif suffix in [".png", ".jpg", ".jpeg", ".webp", ".bmp", ".gif", ".mp3", ".wav", ".ogg"]:
122
- # immagini/audio li gestiamo come path da passare al modello
123
- file_content = uploaded_file
124
- else:
125
- return "Formato file non supportato."
126
 
127
- response = agent(question, context=file_content)
128
- return response
 
 
 
129
 
130
- gr.Interface(
131
- fn=answer_with_media,
132
- inputs=[
133
- gr.Textbox(label="Domanda"),
134
- gr.File(label="Carica file (testo, immagine o audio)")
135
- ],
136
- outputs=gr.Textbox(label="Risposta")
137
- ).launch()
138
 
139
 
140
- '''
141
 
142
 
143
 
 
 
 
 
 
 
 
 
144
  # (Keep Constants as is)
145
  # --- Constants ---
146
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"
 
22
 
23
  class BasicAgent:
24
  def __init__(self):
25
+ print("coso Initializing LlamaIndex-based agent...")
26
 
27
  # Leggi la chiave OpenAI dall'ambiente
28
  openai_api_key = os.getenv("OPENAI_API_KEY")
 
49
 
50
  # Prepara il query engine
51
  self.query_engine = self.index.as_query_engine()
52
+ print("coso Agent ready.")
53
+ '''
54
  def __call__(self, question: str) -> str:
55
  print(f"Received question: {question[:50]}...")
56
  response = self.query_engine.query(question)
 
62
  return str(response)
63
  '''
64
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
65
 
66
+ def __call__(self, question: str) -> str:
67
+ print(f"coso Received question: {question[:100]}")
68
 
69
+ # Prova a decodificare JSON
70
+ try:
71
+ q_data = json.loads(question)
72
+ except json.JSONDecodeError:
73
+ q_data = {"question": question}
74
+
75
+ text = q_data.get("question", "")
76
+ file_info = q_data.get("file")
77
+
78
+ # Se è presente un file, gestiscilo
79
+ if file_info:
80
+ file_name = file_info.get("name", "")
81
+ file_data = file_info.get("data", "")
82
+
83
+ if file_name.endswith((".png", ".jpg", ".jpeg")):
84
+ print("coso Image file detected, processing with GPT-4o")
85
+ image = self._load_image(file_data)
86
+ response = self._ask_gpt4o_with_image(image, text)
87
+ return response
88
+
89
+ elif file_name.endswith(".wav") or file_name.endswith(".mp3"):
90
+ print("coso Audio file detected, processing with Whisper")
91
+ audio_bytes = self._load_bytes(file_data)
92
+ transcription = self._transcribe_audio(audio_bytes)
93
+ return self._ask_gpt4o(transcription)
94
+
95
+ elif file_name.endswith(".txt"):
96
+ print("coso Text file detected")
97
+ text_content = self._load_text(file_data)
98
+ return self._ask_gpt4o(text_content)
99
+
100
+ # Altrimenti gestisci solo testo
101
+ return self._ask_gpt4o(text)
102
+
103
+ def _ask_gpt4o(self, text: str) -> str:
104
+ messages = [{"role": "user", "content": text}]
105
+ response = self.client.chat.completions.create(model="gpt-4o-mini", messages=messages)
106
+ return response.choices[0].message.content.strip()
107
+
108
+ def _ask_gpt4o_with_image(self, image: Image.Image, question: str) -> str:
109
+ buffered = BytesIO()
110
+ image.save(buffered, format="PNG")
111
+ buffered.seek(0)
112
+ image_bytes = buffered.read()
113
+
114
+ response = self.client.chat.completions.create(
115
+ model="gpt-4o-mini",
116
+ messages=[{
117
+ "role": "user",
118
+ "content": [
119
+ {"type": "text", "text": question},
120
+ {"type": "image_url", "image_url": {"url": "data:image/png;base64," + base64.b64encode(image_bytes).decode()}}
121
+ ]
122
+ }]
123
+ )
124
+ return response.choices[0].message.content.strip()
125
 
126
+ def _transcribe_audio(self, audio_bytes: bytes) -> str:
127
+ audio_file = BytesIO(audio_bytes)
128
+ transcription = self.client.audio.transcriptions.create(model="whisper-1", file=audio_file)
129
+ return transcription.text.strip()
130
 
131
+ def _load_image(self, data: str) -> Image.Image:
132
+ return Image.open(BytesIO(base64.b64decode(data)))
 
 
 
 
 
 
133
 
134
+ def _load_bytes(self, data: str) -> bytes:
135
+ return base64.b64decode(data)
136
+
137
+ def _load_text(self, data: str) -> str:
138
+ return base64.b64decode(data).decode("utf-8")
139
 
 
 
 
 
 
 
 
 
140
 
141
 
 
142
 
143
 
144
 
145
+
146
+
147
+
148
+
149
+
150
+
151
+
152
+
153
  # (Keep Constants as is)
154
  # --- Constants ---
155
  DEFAULT_API_URL = "https://agents-course-unit4-scoring.hf.space"