|
import csv
|
|
import os
|
|
import sys
|
|
import base64
|
|
import requests
|
|
import logging
|
|
from pathlib import Path
|
|
|
|
|
|
|
|
API_KEY = "ChiaveAPI"
|
|
MODEL_NAME = "gpt-4o"
|
|
IMAGE_DIR = Path("images")
|
|
CSV_PATH = Path("Dataset_Art-0725.csv")
|
|
OUTPUT_CSV = Path("risposte_output.csv")
|
|
|
|
CATEGORIE = {
|
|
"AR": "art_recognition",
|
|
"CR": "chronological_reasoning",
|
|
"CS": "contextual_summary",
|
|
"VR": "vision_reading",
|
|
"VB": "vision_basic",
|
|
"VL": "vision_logic",
|
|
"VRS": "vision_reasoning",
|
|
"IG" : "img_gen"
|
|
}
|
|
|
|
|
|
|
|
logging.basicConfig(
|
|
filename='task_log.txt',
|
|
level=logging.INFO,
|
|
format='%(asctime)s - %(levelname)s - %(message)s'
|
|
)
|
|
|
|
|
|
|
|
def encode_image(image_path: Path) -> str:
|
|
with open(image_path, "rb") as img:
|
|
return base64.b64encode(img.read()).decode("utf-8")
|
|
|
|
def validate_image_paths(row):
|
|
missing = []
|
|
for col in ['immagine_1_path', 'immagine_2_path']:
|
|
if row[col].strip():
|
|
path = IMAGE_DIR / row[col].strip()
|
|
if not path.exists():
|
|
missing.append(path)
|
|
return missing
|
|
|
|
def invia_task(prompt, image_paths):
|
|
content = [{"type": "text", "text": prompt}]
|
|
for img_path in image_paths:
|
|
if img_path.exists():
|
|
b64 = encode_image(img_path)
|
|
content.append({
|
|
"type": "image_url",
|
|
"image_url": {
|
|
"url": f"data:image/jpeg;base64,{b64}"
|
|
}
|
|
})
|
|
|
|
payload = {
|
|
"model": MODEL_NAME,
|
|
"messages": [
|
|
{
|
|
"role": "system",
|
|
"content": (
|
|
"Sei uno storico dell’arte specializzato in analisi iconografiche e storico-stilistiche. "
|
|
"Rispondi sempre in italiano, in stile accademico, formale e neutrale. "
|
|
"Analizza secondo i criteri storico-artistici e rispondi in modo rigoroso e preciso."
|
|
)
|
|
},
|
|
{"role": "user", "content": content}
|
|
],
|
|
"max_tokens": 1000
|
|
}
|
|
|
|
response = requests.post(
|
|
"https://api.openai.com/v1/chat/completions",
|
|
headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
|
|
json=payload
|
|
)
|
|
|
|
if response.status_code == 200:
|
|
return response.json()["choices"][0]["message"]["content"]
|
|
else:
|
|
raise Exception(f"Errore API: {response.status_code} - {response.text}")
|
|
|
|
|
|
|
|
def main():
|
|
if len(sys.argv) < 2:
|
|
print("Uso: python test_01.py AR CR ...")
|
|
sys.exit(1)
|
|
|
|
categorie_input = sys.argv[1:]
|
|
categorie_mapped = {CATEGORIE[c] for c in categorie_input if c in CATEGORIE}
|
|
|
|
if not categorie_mapped:
|
|
print("Nessuna categoria valida fornita.")
|
|
sys.exit(1)
|
|
|
|
results = []
|
|
|
|
with open(CSV_PATH, encoding='utf-8') as f:
|
|
reader = csv.DictReader(f)
|
|
for idx, row in enumerate(reader, 1):
|
|
if row["categoria"] not in categorie_mapped:
|
|
continue
|
|
|
|
image_paths = [IMAGE_DIR / row["immagine_1_path"].strip()]
|
|
if row["immagine_2_path"].strip():
|
|
image_paths.append(IMAGE_DIR / row["immagine_2_path"].strip())
|
|
|
|
missing = validate_image_paths(row)
|
|
if missing:
|
|
msg = f"[TASK {idx}] Immagini mancanti: {[str(m) for m in missing]}"
|
|
logging.warning(msg)
|
|
print(msg)
|
|
continue
|
|
|
|
|
|
base_prompt = row["prompt"].strip() + " " + row["instructions"].strip()
|
|
opzioni = [row.get("opzione_1", ""), row.get("opzione_2", ""), row.get("opzione_3", "")]
|
|
opzioni = [opt.strip() for opt in opzioni if opt.strip()]
|
|
if opzioni:
|
|
base_prompt += "\n\nOpzioni disponibili:\n" + "\n".join(f"- {opt}" for opt in opzioni)
|
|
|
|
try:
|
|
result = invia_task(base_prompt, image_paths)
|
|
logging.info(f"[TASK {idx}] Completato con successo.")
|
|
results.append({
|
|
"task_id": idx,
|
|
"risposta": result,
|
|
"prompt_inviato": base_prompt
|
|
})
|
|
except Exception as e:
|
|
logging.error(f"[TASK {idx}] Errore durante l'invio: {e}")
|
|
print(f"[TASK {idx}] Errore - vedi log")
|
|
|
|
|
|
if results:
|
|
with open(OUTPUT_CSV, mode='w', encoding='utf-8', newline='') as out_csv:
|
|
writer = csv.DictWriter(out_csv, fieldnames=["task_id", "risposta", "prompt_inviato"])
|
|
writer.writeheader()
|
|
for r in results:
|
|
writer.writerow(r)
|
|
|
|
print(f"Esecuzione completata. Risposte salvate in {OUTPUT_CSV}.")
|
|
|
|
if __name__ == "__main__":
|
|
main()
|
|
|
|
|