paolodegasperis commited on
Commit
e54af64
·
verified ·
1 Parent(s): e88df7e

Update demo_script.py

Browse files
Files changed (1) hide show
  1. demo_script.py +154 -154
demo_script.py CHANGED
@@ -1,154 +1,154 @@
1
- import csv
2
- import os
3
- import sys
4
- import base64
5
- import requests
6
- import logging
7
- from pathlib import Path
8
-
9
- # ==================== CONFIGURAZIONE ====================
10
-
11
- API_KEY = "ChiaveAPI"
12
- MODEL_NAME = "gpt-4o"
13
- IMAGE_DIR = Path("images")
14
- CSV_PATH = Path("Dataset_Art-0725.csv")
15
- OUTPUT_CSV = Path("risposte_output.csv")
16
-
17
- CATEGORIE = {
18
- "AR": "art_recognition",
19
- "CR": "chronological_reasoning",
20
- "CS": "contextual_summary",
21
- "VR": "vision_reading",
22
- "VB": "vision_basic",
23
- "VL": "vision_logic",
24
- "VRS": "vision_reasoning",
25
- "IG" : "img_gen"
26
- }
27
-
28
- # ==================== LOGGING ====================
29
-
30
- logging.basicConfig(
31
- filename='task_log.txt',
32
- level=logging.INFO,
33
- format='%(asctime)s - %(levelname)s - %(message)s'
34
- )
35
-
36
- # ==================== FUNZIONI ====================
37
-
38
- def encode_image(image_path: Path) -> str:
39
- with open(image_path, "rb") as img:
40
- return base64.b64encode(img.read()).decode("utf-8")
41
-
42
- def validate_image_paths(row):
43
- missing = []
44
- for col in ['immagine_1_path', 'immagine_2_path']:
45
- if row[col].strip():
46
- path = IMAGE_DIR / row[col].strip()
47
- if not path.exists():
48
- missing.append(path)
49
- return missing
50
-
51
- def invia_task(prompt, image_paths):
52
- content = [{"type": "text", "text": prompt}]
53
- for img_path in image_paths:
54
- if img_path.exists():
55
- b64 = encode_image(img_path)
56
- content.append({
57
- "type": "image_url",
58
- "image_url": {
59
- "url": f"data:image/jpeg;base64,{b64}"
60
- }
61
- })
62
-
63
- payload = {
64
- "model": MODEL_NAME,
65
- "messages": [
66
- {
67
- "role": "system",
68
- "content": (
69
- "Sei uno storico dell’arte specializzato in analisi iconografiche e storico-stilistiche. "
70
- "Rispondi sempre in italiano, in stile accademico, formale e neutrale. "
71
- "Analizza secondo i criteri storico-artistici e rispondi in modo rigoroso e preciso."
72
- )
73
- },
74
- {"role": "user", "content": content}
75
- ],
76
- "max_tokens": 1000
77
- }
78
-
79
- response = requests.post(
80
- "https://api.openai.com/v1/chat/completions",
81
- headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
82
- json=payload
83
- )
84
-
85
- if response.status_code == 200:
86
- return response.json()["choices"][0]["message"]["content"]
87
- else:
88
- raise Exception(f"Errore API: {response.status_code} - {response.text}")
89
-
90
- # ==================== MAIN ====================
91
-
92
- def main():
93
- if len(sys.argv) < 2:
94
- print("Uso: python test_01.py AR CR ...")
95
- sys.exit(1)
96
-
97
- categorie_input = sys.argv[1:]
98
- categorie_mapped = {CATEGORIE[c] for c in categorie_input if c in CATEGORIE}
99
-
100
- if not categorie_mapped:
101
- print("Nessuna categoria valida fornita.")
102
- sys.exit(1)
103
-
104
- results = []
105
-
106
- with open(CSV_PATH, encoding='utf-8') as f:
107
- reader = csv.DictReader(f)
108
- for idx, row in enumerate(reader, 1):
109
- if row["categoria"] not in categorie_mapped:
110
- continue
111
-
112
- image_paths = [IMAGE_DIR / row["immagine_1_path"].strip()]
113
- if row["immagine_2_path"].strip():
114
- image_paths.append(IMAGE_DIR / row["immagine_2_path"].strip())
115
-
116
- missing = validate_image_paths(row)
117
- if missing:
118
- msg = f"[TASK {idx}] Immagini mancanti: {[str(m) for m in missing]}"
119
- logging.warning(msg)
120
- print(msg)
121
- continue
122
-
123
- # Costruzione del prompt
124
- base_prompt = row["prompt"].strip() + " " + row["instructions"].strip()
125
- opzioni = [row.get("opzione_1", ""), row.get("opzione_2", ""), row.get("opzione_3", "")]
126
- opzioni = [opt.strip() for opt in opzioni if opt.strip()]
127
- if opzioni:
128
- base_prompt += "\n\nOpzioni disponibili:\n" + "\n".join(f"- {opt}" for opt in opzioni)
129
-
130
- try:
131
- result = invia_task(base_prompt, image_paths)
132
- logging.info(f"[TASK {idx}] Completato con successo.")
133
- results.append({
134
- "task_id": idx,
135
- "risposta": result,
136
- "prompt_inviato": base_prompt
137
- })
138
- except Exception as e:
139
- logging.error(f"[TASK {idx}] Errore durante l'invio: {e}")
140
- print(f"[TASK {idx}] Errore - vedi log")
141
-
142
- # Scrittura risultati su CSV
143
- if results:
144
- with open(OUTPUT_CSV, mode='w', encoding='utf-8', newline='') as out_csv:
145
- writer = csv.DictWriter(out_csv, fieldnames=["task_id", "risposta", "prompt_inviato"])
146
- writer.writeheader()
147
- for r in results:
148
- writer.writerow(r)
149
-
150
- print(f"Esecuzione completata. Risposte salvate in {OUTPUT_CSV}.")
151
-
152
- if __name__ == "__main__":
153
- main()
154
-
 
1
+ import csv
2
+ import os
3
+ import sys
4
+ import base64
5
+ import requests
6
+ import logging
7
+ from pathlib import Path
8
+
9
+ # ==================== CONFIGURAZIONE ====================
10
+
11
+ API_KEY = "ChiaveAPI"
12
+ MODEL_NAME = "gpt-4o"
13
+ IMAGE_DIR = Path("images")
14
+ CSV_PATH = Path("ArtVision-0725.csv")
15
+ OUTPUT_CSV = Path("risposte_output.csv")
16
+
17
+ CATEGORIE = {
18
+ "AR": "art_recognition",
19
+ "CR": "chronological_reasoning",
20
+ "CS": "contextual_summary",
21
+ "VR": "vision_reading",
22
+ "VB": "vision_basic",
23
+ "VL": "vision_logic",
24
+ "VRS": "vision_reasoning",
25
+ "IG" : "img_gen"
26
+ }
27
+
28
+ # ==================== LOGGING ====================
29
+
30
+ logging.basicConfig(
31
+ filename='task_log.txt',
32
+ level=logging.INFO,
33
+ format='%(asctime)s - %(levelname)s - %(message)s'
34
+ )
35
+
36
+ # ==================== FUNZIONI ====================
37
+
38
+ def encode_image(image_path: Path) -> str:
39
+ with open(image_path, "rb") as img:
40
+ return base64.b64encode(img.read()).decode("utf-8")
41
+
42
+ def validate_image_paths(row):
43
+ missing = []
44
+ for col in ['immagine_1_path', 'immagine_2_path']:
45
+ if row[col].strip():
46
+ path = IMAGE_DIR / row[col].strip()
47
+ if not path.exists():
48
+ missing.append(path)
49
+ return missing
50
+
51
+ def invia_task(prompt, image_paths):
52
+ content = [{"type": "text", "text": prompt}]
53
+ for img_path in image_paths:
54
+ if img_path.exists():
55
+ b64 = encode_image(img_path)
56
+ content.append({
57
+ "type": "image_url",
58
+ "image_url": {
59
+ "url": f"data:image/jpeg;base64,{b64}"
60
+ }
61
+ })
62
+
63
+ payload = {
64
+ "model": MODEL_NAME,
65
+ "messages": [
66
+ {
67
+ "role": "system",
68
+ "content": (
69
+ "Sei uno storico dell’arte specializzato in analisi iconografiche e storico-stilistiche. "
70
+ "Rispondi sempre in italiano, in stile accademico, formale e neutrale. "
71
+ "Analizza secondo i criteri storico-artistici e rispondi in modo rigoroso e preciso."
72
+ )
73
+ },
74
+ {"role": "user", "content": content}
75
+ ],
76
+ "max_tokens": 1000
77
+ }
78
+
79
+ response = requests.post(
80
+ "https://api.openai.com/v1/chat/completions",
81
+ headers={"Authorization": f"Bearer {API_KEY}", "Content-Type": "application/json"},
82
+ json=payload
83
+ )
84
+
85
+ if response.status_code == 200:
86
+ return response.json()["choices"][0]["message"]["content"]
87
+ else:
88
+ raise Exception(f"Errore API: {response.status_code} - {response.text}")
89
+
90
+ # ==================== MAIN ====================
91
+
92
+ def main():
93
+ if len(sys.argv) < 2:
94
+ print("Uso: python test_01.py AR CR ...")
95
+ sys.exit(1)
96
+
97
+ categorie_input = sys.argv[1:]
98
+ categorie_mapped = {CATEGORIE[c] for c in categorie_input if c in CATEGORIE}
99
+
100
+ if not categorie_mapped:
101
+ print("Nessuna categoria valida fornita.")
102
+ sys.exit(1)
103
+
104
+ results = []
105
+
106
+ with open(CSV_PATH, encoding='utf-8') as f:
107
+ reader = csv.DictReader(f)
108
+ for idx, row in enumerate(reader, 1):
109
+ if row["categoria"] not in categorie_mapped:
110
+ continue
111
+
112
+ image_paths = [IMAGE_DIR / row["immagine_1_path"].strip()]
113
+ if row["immagine_2_path"].strip():
114
+ image_paths.append(IMAGE_DIR / row["immagine_2_path"].strip())
115
+
116
+ missing = validate_image_paths(row)
117
+ if missing:
118
+ msg = f"[TASK {idx}] Immagini mancanti: {[str(m) for m in missing]}"
119
+ logging.warning(msg)
120
+ print(msg)
121
+ continue
122
+
123
+ # Costruzione del prompt
124
+ base_prompt = row["prompt"].strip() + " " + row["instructions"].strip()
125
+ opzioni = [row.get("opzione_1", ""), row.get("opzione_2", ""), row.get("opzione_3", "")]
126
+ opzioni = [opt.strip() for opt in opzioni if opt.strip()]
127
+ if opzioni:
128
+ base_prompt += "\n\nOpzioni disponibili:\n" + "\n".join(f"- {opt}" for opt in opzioni)
129
+
130
+ try:
131
+ result = invia_task(base_prompt, image_paths)
132
+ logging.info(f"[TASK {idx}] Completato con successo.")
133
+ results.append({
134
+ "task_id": idx,
135
+ "risposta": result,
136
+ "prompt_inviato": base_prompt
137
+ })
138
+ except Exception as e:
139
+ logging.error(f"[TASK {idx}] Errore durante l'invio: {e}")
140
+ print(f"[TASK {idx}] Errore - vedi log")
141
+
142
+ # Scrittura risultati su CSV
143
+ if results:
144
+ with open(OUTPUT_CSV, mode='w', encoding='utf-8', newline='') as out_csv:
145
+ writer = csv.DictWriter(out_csv, fieldnames=["task_id", "risposta", "prompt_inviato"])
146
+ writer.writeheader()
147
+ for r in results:
148
+ writer.writerow(r)
149
+
150
+ print(f"Esecuzione completata. Risposte salvate in {OUTPUT_CSV}.")
151
+
152
+ if __name__ == "__main__":
153
+ main()
154
+