File size: 4,986 Bytes
e54af64 d33f001 e54af64 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | import csv
import os
import sys
import base64
import requests
import logging
from pathlib import Path
# ==================== CONFIGURAZIONE ====================
API_KEY = "ChiaveAPI"
MODEL_NAME = "gpt-4o"
IMAGE_DIR = Path("images")
CSV_PATH = Path("ArtVision-0825.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 ====================
logging.basicConfig(
filename='task_log.txt',
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s'
)
# ==================== FUNZIONI ====================
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}")
# ==================== MAIN ====================
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
# Costruzione del prompt
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")
# Scrittura risultati su CSV
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()
|