laura.wagner commited on
Commit
263b6e9
·
1 Parent(s): 0f34c19

corrected LLM query code

Browse files
.gitignore CHANGED
@@ -8,4 +8,5 @@ misc/credentials
8
  scripts/ARCHIVE
9
  scripts/CEMETARY
10
  cemetary
11
- .venv
 
 
8
  scripts/ARCHIVE
9
  scripts/CEMETARY
10
  cemetary
11
+ .venv
12
+ logs
jupyter_notebooks/.ipynb_checkpoints/Section_2-3_Figure_5_co-occurence_promotional_tags-checkpoint.ipynb ADDED
@@ -0,0 +1,314 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "cells": [
3
+ {
4
+ "cell_type": "markdown",
5
+ "metadata": {},
6
+ "source": [
7
+ "# Create *.json for figure 5 (Co-occurence network of Tags)"
8
+ ]
9
+ },
10
+ {
11
+ "cell_type": "code",
12
+ "execution_count": 5,
13
+ "metadata": {},
14
+ "outputs": [
15
+ {
16
+ "name": "stdout",
17
+ "output_type": "stream",
18
+ "text": [
19
+ "Processing: america\n",
20
+ " ✅ Saved to /home/lauhp/000_PHD/000_010_PUBLICATION/2025_SAGE/CODE/pm-paper_uzh_gitlab/pm-paper/public/json/tags_america.json\n"
21
+ ]
22
+ }
23
+ ],
24
+ "source": [
25
+ "import pandas as pd\n",
26
+ "from itertools import combinations\n",
27
+ "from collections import Counter, defaultdict\n",
28
+ "import json\n",
29
+ "import re\n",
30
+ "import os\n",
31
+ "\n",
32
+ "from pathlib import Path\n",
33
+ "current_dir = Path.cwd()\n",
34
+ "\n",
35
+ "# === CONFIG ===\n",
36
+ "file_path = current_dir.parent / \"data/CSV/Models/Civi_models.csv\"\n",
37
+ "output_dir = current_dir.parent / \"public/json/\"\n",
38
+ "#target_terms = [\"asian\", \"indian\", \"man\", \"woman\", \"german\", \"korean\", \"american\", \"russian\", \"style\", \"japanese\", \"chinese\"] # Add any tags you want to process\n",
39
+ "#target_terms = [\"character\", \"instagram\", \"youtuber\", \"actor\", \"actress\", \"celebrity\", \"vtuber\", \"kpop\"] # Add any tags you want to process\n",
40
+ "target_terms = [\"america\"] # Add any tags you want to process\n",
41
+ "min_connections = 1 # minimum number of link connections per node\n",
42
+ "\n",
43
+ "# === LOAD DATA ===\n",
44
+ "df = pd.read_csv(file_path)\n",
45
+ "tag_columns = [f\"tag_{i}\" for i in range(1, 8)]\n",
46
+ "df_tags = df[tag_columns]\n",
47
+ "\n",
48
+ "# === MAIN LOOP ===\n",
49
+ "for target_term in target_terms:\n",
50
+ " print(f\"Processing: {target_term}\")\n",
51
+ " \n",
52
+ " pattern = re.compile(rf'\\b{re.escape(target_term)}\\b', flags=re.IGNORECASE)\n",
53
+ " df_filtered = df_tags[df_tags.apply(\n",
54
+ " lambda row: row.astype(str).apply(lambda x: bool(pattern.search(x))).any(),\n",
55
+ " axis=1\n",
56
+ " )]\n",
57
+ "\n",
58
+ " # Skip if no data matches\n",
59
+ " if df_filtered.empty:\n",
60
+ " print(f\" ⚠️ No matches for '{target_term}', skipping.\")\n",
61
+ " continue\n",
62
+ "\n",
63
+ " # === COUNT INDIVIDUAL TAGS ===\n",
64
+ " all_tags = df_filtered.values.flatten()\n",
65
+ " all_tags = [tag for tag in all_tags if pd.notna(tag)]\n",
66
+ " tag_counts = Counter(all_tags)\n",
67
+ "\n",
68
+ " # === CO-OCCURRENCE ===\n",
69
+ " co_occurrences = defaultdict(int)\n",
70
+ " for tags in df_filtered.itertuples(index=False, name=None):\n",
71
+ " tags = [tag for tag in tags if pd.notna(tag)]\n",
72
+ " for tag1, tag2 in combinations(tags, 2):\n",
73
+ " co_occurrences[frozenset([tag1, tag2])] += 1\n",
74
+ "\n",
75
+ " edges = [(list(pair)[0], list(pair)[1], weight) for pair, weight in co_occurrences.items()]\n",
76
+ "\n",
77
+ " # === FILTER BY CONNECTIONS ===\n",
78
+ " connected_tags = Counter()\n",
79
+ " for tag1, tag2, _ in edges:\n",
80
+ " connected_tags[tag1] += 1\n",
81
+ " connected_tags[tag2] += 1\n",
82
+ "\n",
83
+ " nodes = [{\"id\": tag, \"size\": tag_counts[tag]} for tag in tag_counts if connected_tags[tag] >= min_connections]\n",
84
+ " valid_ids = set(node[\"id\"] for node in nodes)\n",
85
+ " links = [{\"source\": tag1, \"target\": tag2, \"value\": weight}\n",
86
+ " for tag1, tag2, weight in edges\n",
87
+ " if tag1 in valid_ids and tag2 in valid_ids]\n",
88
+ "\n",
89
+ " if not nodes or not links:\n",
90
+ " print(f\" ⚠️ Not enough connections for '{target_term}', skipping.\")\n",
91
+ " continue\n",
92
+ "\n",
93
+ " # === EXPORT ===\n",
94
+ " d3_data = {\"nodes\": nodes, \"links\": links}\n",
95
+ " safe_term = re.sub(r'\\W+', '_', target_term.lower())\n",
96
+ " output_file = os.path.join(output_dir, f\"tags_{safe_term}.json\")\n",
97
+ " \n",
98
+ " with open(output_file, \"w\") as f:\n",
99
+ " json.dump(d3_data, f, indent=4)\n",
100
+ " \n",
101
+ " print(f\" ✅ Saved to {output_file}\")\n"
102
+ ]
103
+ },
104
+ {
105
+ "cell_type": "markdown",
106
+ "metadata": {},
107
+ "source": [
108
+ "## Different Countries"
109
+ ]
110
+ },
111
+ {
112
+ "cell_type": "code",
113
+ "execution_count": 2,
114
+ "metadata": {},
115
+ "outputs": [
116
+ {
117
+ "name": "stderr",
118
+ "output_type": "stream",
119
+ "text": [
120
+ "/tmp/ipykernel_68582/2797381217.py:15: DtypeWarning: Columns (50,51,54,55,56,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,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,458) have mixed types. Specify dtype option on import or set low_memory=False.\n",
121
+ " df = pd.read_csv(file_path)\n"
122
+ ]
123
+ },
124
+ {
125
+ "name": "stdout",
126
+ "output_type": "stream",
127
+ "text": [
128
+ "Processing: united states\n",
129
+ " ⚠️ No matches for 'united states', skipping.\n",
130
+ "Processing: korea\n",
131
+ " ✅ Saved to data/json/tags_korea_poi.json\n",
132
+ "Processing: uk\n",
133
+ " ✅ Saved to data/json/tags_uk_poi.json\n",
134
+ "Processing: russia\n",
135
+ " ✅ Saved to data/json/tags_russia_poi.json\n",
136
+ "Processing: china\n",
137
+ " ✅ Saved to data/json/tags_china_poi.json\n",
138
+ "Processing: canada\n",
139
+ " ✅ Saved to data/json/tags_canada_poi.json\n",
140
+ "Processing: India\n",
141
+ " ✅ Saved to data/json/tags_india_poi.json\n",
142
+ "Processing: germany\n",
143
+ " ✅ Saved to data/json/tags_germany_poi.json\n"
144
+ ]
145
+ }
146
+ ],
147
+ "source": [
148
+ "import pandas as pd\n",
149
+ "from itertools import combinations\n",
150
+ "from collections import Counter, defaultdict\n",
151
+ "import json\n",
152
+ "import re\n",
153
+ "import os\n",
154
+ "\n",
155
+ "# === CONFIG ===\n",
156
+ "file_path = \"data/model_subsets/all_models_poi_true.csv\"\n",
157
+ "output_dir = \"data/json/\"\n",
158
+ "target_terms = [\"united states\", \"korea\", \"uk\", \"russia\", \"china\", \"canada\", \"India\", \"germany\"] # Add any tags you want to process\n",
159
+ "min_connections = 1 # minimum number of link connections per node\n",
160
+ "\n",
161
+ "# === LOAD DATA ===\n",
162
+ "df = pd.read_csv(file_path)\n",
163
+ "tag_columns = [f\"tag_{i}\" for i in range(1, 8)]\n",
164
+ "df_tags = df[tag_columns]\n",
165
+ "\n",
166
+ "# === MAIN LOOP ===\n",
167
+ "for target_term in target_terms:\n",
168
+ " print(f\"Processing: {target_term}\")\n",
169
+ " \n",
170
+ " pattern = re.compile(rf'\\b{re.escape(target_term)}\\b', flags=re.IGNORECASE)\n",
171
+ " df_filtered = df_tags[df_tags.apply(\n",
172
+ " lambda row: row.astype(str).apply(lambda x: bool(pattern.search(x))).any(),\n",
173
+ " axis=1\n",
174
+ " )]\n",
175
+ "\n",
176
+ " # Skip if no data matches\n",
177
+ " if df_filtered.empty:\n",
178
+ " print(f\" ⚠️ No matches for '{target_term}', skipping.\")\n",
179
+ " continue\n",
180
+ "\n",
181
+ " # === COUNT INDIVIDUAL TAGS ===\n",
182
+ " all_tags = df_filtered.values.flatten()\n",
183
+ " all_tags = [tag for tag in all_tags if pd.notna(tag)]\n",
184
+ " tag_counts = Counter(all_tags)\n",
185
+ "\n",
186
+ " # === CO-OCCURRENCE ===\n",
187
+ " co_occurrences = defaultdict(int)\n",
188
+ " for tags in df_filtered.itertuples(index=False, name=None):\n",
189
+ " tags = [tag for tag in tags if pd.notna(tag)]\n",
190
+ " for tag1, tag2 in combinations(tags, 2):\n",
191
+ " co_occurrences[frozenset([tag1, tag2])] += 1\n",
192
+ "\n",
193
+ " edges = [(list(pair)[0], list(pair)[1], weight) for pair, weight in co_occurrences.items()]\n",
194
+ "\n",
195
+ " # === FILTER BY CONNECTIONS ===\n",
196
+ " connected_tags = Counter()\n",
197
+ " for tag1, tag2, _ in edges:\n",
198
+ " connected_tags[tag1] += 1\n",
199
+ " connected_tags[tag2] += 1\n",
200
+ "\n",
201
+ " nodes = [{\"id\": tag, \"size\": tag_counts[tag]} for tag in tag_counts if connected_tags[tag] >= min_connections]\n",
202
+ " valid_ids = set(node[\"id\"] for node in nodes)\n",
203
+ " links = [{\"source\": tag1, \"target\": tag2, \"value\": weight}\n",
204
+ " for tag1, tag2, weight in edges\n",
205
+ " if tag1 in valid_ids and tag2 in valid_ids]\n",
206
+ "\n",
207
+ " if not nodes or not links:\n",
208
+ " print(f\" ⚠️ Not enough connections for '{target_term}', skipping.\")\n",
209
+ " continue\n",
210
+ "\n",
211
+ " # === EXPORT ===\n",
212
+ " d3_data = {\"nodes\": nodes, \"links\": links}\n",
213
+ " safe_term = re.sub(r'\\W+', '_', target_term.lower())\n",
214
+ " output_file = os.path.join(output_dir, f\"tags_{safe_term}_poi.json\")\n",
215
+ " \n",
216
+ " with open(output_file, \"w\") as f:\n",
217
+ " json.dump(d3_data, f, indent=4)\n",
218
+ " \n",
219
+ " print(f\" ✅ Saved to {output_file}\")\n"
220
+ ]
221
+ },
222
+ {
223
+ "cell_type": "code",
224
+ "execution_count": 5,
225
+ "metadata": {},
226
+ "outputs": [
227
+ {
228
+ "name": "stderr",
229
+ "output_type": "stream",
230
+ "text": [
231
+ "/tmp/ipykernel_79893/1420003123.py:13: DtypeWarning: Columns (50,51,54,55,56,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,156,157,158,159,160,161,162,163,164,165,166,167,168,169,170,171,172,173,174,175,176,177,178,179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,215,216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,248,249,250,251,252,253,254,255,256,257,458) have mixed types. Specify dtype option on import or set low_memory=False.\n",
232
+ " df = pd.read_csv(file_path)\n"
233
+ ]
234
+ },
235
+ {
236
+ "name": "stdout",
237
+ "output_type": "stream",
238
+ "text": [
239
+ "✅ Exported 60330 nodes and 16921 links to public/json/nodes_all.json\n"
240
+ ]
241
+ }
242
+ ],
243
+ "source": [
244
+ "import pandas as pd\n",
245
+ "from itertools import combinations\n",
246
+ "from collections import Counter, defaultdict\n",
247
+ "import json\n",
248
+ "import os\n",
249
+ "\n",
250
+ "# === CONFIG ===\n",
251
+ "file_path = \"data/model_subsets/all_models_poi_false.csv\"\n",
252
+ "output_file = \"public/json/nodes_all.json\"\n",
253
+ "min_link_threshold = 10 # Only keep edges with co-occurrence >= this\n",
254
+ "\n",
255
+ "# === LOAD DATA ===\n",
256
+ "df = pd.read_csv(file_path)\n",
257
+ "tag_columns = [f\"tag_{i}\" for i in range(1, 8)]\n",
258
+ "df_tags = df[tag_columns]\n",
259
+ "\n",
260
+ "# === COUNT INDIVIDUAL TAGS ===\n",
261
+ "all_tags = df_tags.values.flatten()\n",
262
+ "all_tags = [tag for tag in all_tags if pd.notna(tag)]\n",
263
+ "tag_counts = Counter(all_tags)\n",
264
+ "\n",
265
+ "# === CO-OCCURRENCE ===\n",
266
+ "co_occurrences = defaultdict(int)\n",
267
+ "for tags in df_tags.itertuples(index=False, name=None):\n",
268
+ " tags = [tag for tag in tags if pd.notna(tag)]\n",
269
+ " for tag1, tag2 in combinations(tags, 2):\n",
270
+ " co_occurrences[frozenset([tag1, tag2])] += 1\n",
271
+ "\n",
272
+ "# === Build Edges (Filtered by co-occurrence threshold)\n",
273
+ "edges = [\n",
274
+ " {\"source\": list(pair)[0], \"target\": list(pair)[1], \"value\": weight}\n",
275
+ " for pair, weight in co_occurrences.items()\n",
276
+ " if weight >= min_link_threshold\n",
277
+ "]\n",
278
+ "\n",
279
+ "# === Build Nodes (All tags that appear, regardless of links)\n",
280
+ "nodes = [{\"id\": tag, \"size\": tag_counts[tag]} for tag in tag_counts]\n",
281
+ "\n",
282
+ "# === EXPORT ===\n",
283
+ "d3_data = {\"nodes\": nodes, \"links\": edges}\n",
284
+ "\n",
285
+ "os.makedirs(os.path.dirname(output_file), exist_ok=True)\n",
286
+ "with open(output_file, \"w\") as f:\n",
287
+ " json.dump(d3_data, f, indent=4)\n",
288
+ "\n",
289
+ "print(f\"✅ Exported {len(nodes)} nodes and {len(edges)} links to {output_file}\")\n"
290
+ ]
291
+ }
292
+ ],
293
+ "metadata": {
294
+ "kernelspec": {
295
+ "display_name": "latm",
296
+ "language": "python",
297
+ "name": "python3"
298
+ },
299
+ "language_info": {
300
+ "codemirror_mode": {
301
+ "name": "ipython",
302
+ "version": 3
303
+ },
304
+ "file_extension": ".py",
305
+ "mimetype": "text/x-python",
306
+ "name": "python",
307
+ "nbconvert_exporter": "python",
308
+ "pygments_lexer": "ipython3",
309
+ "version": "3.10.15"
310
+ }
311
+ },
312
+ "nbformat": 4,
313
+ "nbformat_minor": 2
314
+ }
jupyter_notebooks/Section_2-3-4_Bloomz_query.ipynb CHANGED
@@ -2,414 +2,328 @@
2
  "cells": [
3
  {
4
  "cell_type": "code",
5
- "execution_count": null,
6
  "id": "3b87c378-241e-41ab-be6e-84222594f22f",
7
- "metadata": {},
 
 
 
 
 
 
 
 
8
  "outputs": [],
9
  "source": [
10
- "import pandas as pd",
11
- "import json",
12
- "import time",
13
- "import re",
14
- "from pathlib import Path",
15
- "from tqdm import tqdm",
16
- "import torch",
17
- "from transformers import AutoModelForCausalLM, AutoTokenizer",
18
- "from datetime import datetime",
19
- "",
20
- "# Import is used for pd.notna() and pd.isna() checks",
21
- "",
22
- "current_dir = Path.cwd())",
23
- "input_file = current_dir.parent / \"data/CSV/model_adapter/real_person_adapter_step_02_NER.csv\"",
24
- "",
25
- "# === CONFIGURATION ===",
26
- "TEST_MODE = True",
27
- "TEST_SIZE = 10",
28
- "MAX_ROWS = 20000",
29
- "SAVE_INTERVAL = 10",
30
- "",
31
- "# Model settings - BLOOMZ (BigScience - European consortium)",
32
- "MODEL_NAME = \"bigscience/bloomz-7b1\" # Largest instruction-tuned BLOOM model",
33
- "CACHE_DIR = current_dir.parent / \"data/models\"",
34
- "CACHE_DIR.mkdir(parents=True, exist_ok=True)",
35
- "",
36
- "PROFESSION_CATEGORIES = [",
37
- " \"actor\", \"adult performer\", \"singer/musician\", \"model\",",
38
- " \"online personality\", \"public figure\", \"voice actor/ASMR\",",
39
- " \"sports professional\", \"tv personality\"",
40
- "]",
41
- "",
42
- "# === LOAD MODEL ===",
43
- "print(f\"Loading model: {MODEL_NAME}\")",
44
- "print(f\"Cache directory: {CACHE_DIR}\")",
45
- "print(f\"This may take a while on first run (~14GB download)...\\n\")",
46
- "",
47
- "# Check GPU availability",
48
- "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"",
49
- "print(f\"Device: {device}\")",
50
- "",
51
- "if device == \"cpu\":",
52
- " print(\"\u26a0\ufe0f WARNING: No GPU detected! Inference will be VERY slow.\")",
53
- " print(\" Consider using a GPU or reducing model size.\")",
54
- "",
55
- "# Load tokenizer",
56
- "print(\"Loading tokenizer...\")",
57
- "try:",
58
- " tokenizer = AutoTokenizer.from_pretrained(",
59
- " MODEL_NAME,",
60
- " cache_dir=str(CACHE_DIR)",
61
- " )",
62
- " print(\"\u2705 Tokenizer loaded\")",
63
- "except Exception as e:",
64
- " print(f\"\u274c Error loading tokenizer: {e}\")",
65
- " raise",
66
- "",
67
- "# Ensure pad token is set",
68
- "if tokenizer.pad_token is None:",
69
- " tokenizer.pad_token = tokenizer.eos_token",
70
- " print(f\"Set pad_token to eos_token: {tokenizer.eos_token}\")",
71
- "",
72
- "# Load model with optimizations",
73
- "print(\"Loading model (this may take several minutes)...\")",
74
- "try:",
75
- " model = AutoModelForCausalLM.from_pretrained(",
76
- " MODEL_NAME,",
77
- " cache_dir=str(CACHE_DIR),",
78
- " torch_dtype=torch.bfloat16, # Use BF16 for efficiency",
79
- " device_map=\"auto\", # Automatically distribute across GPUs",
80
- " low_cpu_mem_usage=True # Optimize memory usage",
81
- " )",
82
- " model.eval() # Set to evaluation mode",
83
- " print(\"\u2705 Model loaded\")",
84
- "except Exception as e:",
85
- " print(f\"\u274c Error loading model: {e}\")",
86
- " raise",
87
- "",
88
- "# Check VRAM usage",
89
- "if torch.cuda.is_available():",
90
- " vram_gb = torch.cuda.max_memory_allocated() / 1024**3",
91
- " print(f\"VRAM used: {vram_gb:.2f} GB\\n\")",
92
- "",
93
- "# === LOAD DATA ===",
94
- "df = pd.read_csv(input_file)",
95
- "print(f\"Loaded {len(df)} rows\")",
96
- "",
97
- "if TEST_MODE:",
98
- " print(f\"Running in TEST MODE with {TEST_SIZE} samples\")",
99
- " df = df.head(TEST_SIZE).copy()",
100
- "elif MAX_ROWS:",
101
- " df = df.head(MAX_ROWS).copy()",
102
- "",
103
- "# === CREATE PROMPT (Exact DeepSeek style) ===",
104
- "def create_prompt(row):",
105
- " \"\"\"Create prompt.\"\"\"",
106
- " name = row.get('real_name', row.get('name', ''))",
107
- " if pd.isna(name):",
108
- " name = row.get('name', '')",
109
- "",
110
- " # Gather hints exactly like DeepSeek version",
111
- " hints = []",
112
- " if pd.notna(row.get('likely_profession')):",
113
- " hints.append(str(row['likely_profession']))",
114
- " if pd.notna(row.get('likely_nationality')):",
115
- " hints.append(str(row['likely_nationality']))",
116
- " if pd.notna(row.get('likely_country')):",
117
- " hints.append(str(row['likely_country']))",
118
- "",
119
- " # Add tags if we don't have enough hints",
120
- " if len(hints) < 3:",
121
- " for i in range(1, 8):",
122
- " tag_col = f'tag_{i}'",
123
- " if tag_col in row and pd.notna(row[tag_col]):",
124
- " tag_val = str(row[tag_col])",
125
- " if tag_val not in hints:",
126
- " hints.append(tag_val)",
127
- " if len(hints) >= 5:",
128
- " break",
129
- "",
130
- " hint_text = \", \".join(hints[:5]) if hints else \"none\"",
131
- "",
132
- " return f\"\"\"Given '{name}' ({hint_text}), provide:",
133
- "1. Full legal name (Western order if non-latin script)",
134
- "2. Any stage names/aliases (comma separated)",
135
- "3. Gender (Male/Female/Other/Unknown)",
136
- "4. Top 3 most likely professions from ONLY these categories:",
137
- " - actor",
138
- " - adult performer",
139
- " - singer/musician",
140
- " - model",
141
- " - online personality (includes streamers, cosplayers, influencers)",
142
- " - public figure (includes politicians, activists, journalists, authors)",
143
- " - voice actor/ASMR",
144
- " - sports professional",
145
- " - tv personality (includes hosts, presenters, reality TV)",
146
- "",
147
- "5. Primary country associated",
148
- "",
149
- "IMPORTANT:",
150
- "- Choose professions ONLY from the 9 categories above",
151
- "- Provide up to 3 professions, comma-separated, ordered by relevance",
152
- "- Be SPECIFIC: choose the most accurate category for each role",
153
- "- \"online personality\" includes: streamers, cosplayers, YouTubers, influencers, content creators",
154
- "- Use 'Unknown' when uncertain or for fictional characters/places",
155
- "- For multi-role people, list all relevant categories (e.g., \"actor, singer/musician, online personality\")",
156
- "",
157
- "Respond with exactly 5 numbered lines.\"\"\"",
158
- "",
159
- "df['prompt'] = df.apply(create_prompt, axis=1)",
160
- "",
161
- "# === SETUP LOGGING ===",
162
- "log_dir = current_dir.parent / \"logs\"",
163
- "log_dir.mkdir(parents=True, exist_ok=True)",
164
- "log_file = log_dir / f\"bloomz_responses_{datetime.now().strftime('%Y%m%d_%H%M%S')}.log\"",
165
- "",
166
- "def log_response(idx, name, prompt, full_prompt, raw_response, parsed_data):",
167
- " \"\"\"Log all BLOOM responses to file for debugging.\"\"\"",
168
- " with open(log_file, 'a', encoding='utf-8') as f:",
169
- " f.write(f\"{'='*80}\\n\")",
170
- " f.write(f\"INDEX: {idx}\\n\")",
171
- " f.write(f\"NAME: {name}\\n\")",
172
- " f.write(f\"TIMESTAMP: {datetime.now().isoformat()}\\n\")",
173
- " f.write(f\"\\n--- ORIGINAL PROMPT ---\\n{prompt}\\n\")",
174
- " f.write(f\"\\n--- FULL PROMPT SENT TO MODEL ---\\n{full_prompt}\\n\")",
175
- " f.write(f\"\\n--- RAW MODEL RESPONSE ---\\n{raw_response}\\n\")",
176
- " f.write(f\"\\n--- PARSED DATA ---\\n{json.dumps(parsed_data, indent=2)}\\n\")",
177
- " f.write(f\"{'='*80}\\n\\n\")",
178
- "",
179
- "print(f\"\ud83d\udcdd Logging BLOOM responses to: {log_file}\\n\")",
180
- "",
181
- "# === QUERY BLOOMZ LOCAL (IMPROVED WITH FEW-SHOT) ===",
182
- "def query_bloomz_local(prompt: str) -> str:",
183
- " \"\"\"Query BLOOMZ-7B1 locally via transformers, return raw response string.",
184
- "",
185
- " Uses few-shot prompting which works much better for BLOOMZ.",
186
- " \"\"\"",
187
- " try:",
188
- " # Extract name and hints from the original prompt",
189
- " # Format: \"Given 'Name' (hints), provide:\"",
190
- " name_match = re.search(r\"Given '([^']+)' \\(([^)]+)\\)\", prompt)",
191
- " if name_match:",
192
- " name = name_match.group(1)",
193
- " hints = name_match.group(2)",
194
- " else:",
195
- " name = \"Unknown\"",
196
- " hints = \"no hints\"",
197
- "",
198
- " # BLOOMZ responds MUCH better to few-shot examples than long instructions",
199
- " full_prompt = f\"\"\"Extract person information in 5 numbered lines.",
200
- "",
201
- "Example 1:",
202
- "Name: Scarlett Johansson (actor, model)",
203
- "1. Scarlett Ingrid Johansson",
204
- "2. ScarJo",
205
- "3. Female",
206
- "4. actor, model",
207
- "5. United States",
208
- "",
209
- "Example 2:",
210
- "Name: Ed Sheeran (singer, musician)",
211
- "1. Edward Christopher Sheeran",
212
- "2. Ed Sheeran",
213
- "3. Male",
214
- "4. singer/musician",
215
- "5. United Kingdom",
216
- "",
217
- "Example 3:",
218
- "Name: Amouranth (streamer, cosplayer, model)",
219
- "1. Kaitlyn Siragusa",
220
- "2. Amouranth",
221
- "3. Female",
222
- "4. online personality, model",
223
- "5. United States",
224
- "",
225
- "Now extract for:",
226
- "Name: {name} ({hints})",
227
- "1.\"\"\"",
228
- "",
229
- " # Store full prompt for logging",
230
- " query_bloomz_local.last_full_prompt = full_prompt",
231
- "",
232
- " inputs = tokenizer(",
233
- " full_prompt,",
234
- " return_tensors=\"pt\",",
235
- " truncation=True,",
236
- " max_length=2048",
237
- " ).to(device)",
238
- "",
239
- " # Generate with adjusted parameters for BLOOMZ",
240
- " with torch.no_grad():",
241
- " outputs = model.generate(",
242
- " **inputs,",
243
- " max_new_tokens=256,",
244
- " temperature=0.3, # Increased for more variability",
245
- " do_sample=True,",
246
- " top_p=0.9,",
247
- " top_k=40,",
248
- " repetition_penalty=1.1,",
249
- " pad_token_id=tokenizer.eos_token_id, # Use EOS as pad token",
250
- " eos_token_id=tokenizer.eos_token_id,",
251
- " early_stopping=True",
252
- " )",
253
- "",
254
- " # Decode the entire output to see what's happening",
255
- " full_output = tokenizer.decode(outputs[0], skip_special_tokens=True)",
256
- "",
257
- " # Extract only the generated part (after the prompt)",
258
- " generated_text = full_output[len(tokenizer.decode(inputs['input_ids'][0], skip_special_tokens=True)):]",
259
- "",
260
- " # Debug output (show first 3)",
261
- " if not hasattr(query_bloomz_local, 'debug_count'):",
262
- " query_bloomz_local.debug_count = 0",
263
- "",
264
- " if query_bloomz_local.debug_count < 3:",
265
- " print(f\"\\n\ud83d\udcdd BLOOMZ Debug #{query_bloomz_local.debug_count + 1}:\")",
266
- " print(f\"Input: {name} ({hints})\")",
267
- " print(f\"Generated: {generated_text[:200]}\")",
268
- " print(f\"{'='*60}\\n\")",
269
- " query_bloomz_local.debug_count += 1",
270
- "",
271
- " return generated_text.strip()",
272
- "",
273
- " except Exception as e:",
274
- " print(f\"Error querying BLOOMZ: {e}\")",
275
- " query_bloomz_local.last_full_prompt = f\"ERROR: {e}\"",
276
- " return None",
277
- "",
278
- "# === PARSE RESPONSE (Exact DeepSeek format) ===",
279
- "def parse_response(response):",
280
- " \"\"\"Parse numbered response into structured fields.\"\"\"",
281
- " if not response:",
282
- " return {",
283
- " 'full_name': 'Unknown',",
284
- " 'aliases': 'Unknown',",
285
- " 'gender': 'Unknown',",
286
- " 'profession_llm': 'Unknown',",
287
- " 'country': 'Unknown'",
288
- " }",
289
- "",
290
- " # Split into lines and clean",
291
- " lines = [line.strip() for line in response.split('\\n') if line.strip()]",
292
- "",
293
- " # Initialize with Unknown values",
294
- " fields = {",
295
- " 'full_name': 'Unknown',",
296
- " 'aliases': 'Unknown',",
297
- " 'gender': 'Unknown',",
298
- " 'profession_llm': 'Unknown',",
299
- " 'country': 'Unknown'",
300
- " }",
301
- "",
302
- " # Extract information from each numbered line",
303
- " for line in lines:",
304
- " if line.startswith('1.') or line.startswith('1)'):",
305
- " fields['full_name'] = line[2:].strip()",
306
- " elif line.startswith('2.') or line.startswith('2)'):",
307
- " fields['aliases'] = line[2:].strip()",
308
- " elif line.startswith('3.') or line.startswith('3)'):",
309
- " fields['gender'] = line[2:].strip()",
310
- " elif line.startswith('4.') or line.startswith('4)'):",
311
- " fields['profession_llm'] = line[2:].strip()",
312
- " elif line.startswith('5.') or line.startswith('5)'):",
313
- " fields['country'] = line[2:].strip()",
314
- "",
315
- " return fields",
316
- "",
317
- "# === PROCESS ===",
318
- "output_file = current_dir.parent / f\"data/CSV/bloomz_annotated_POI{'_test' if TEST_MODE else ''}.csv\"",
319
- "index_file = current_dir.parent / \"misc/bloomz_query_index.txt\"",
320
- "",
321
- "current_index = 0",
322
- "if index_file.exists():",
323
- " with open(index_file) as f:",
324
- " current_index = int(f.read().strip())",
325
- " print(f\"Resuming from index {current_index}\")",
326
- "",
327
- "# Initialize columns (same as DeepSeek)",
328
- "for col in ['full_name', 'gender', 'profession_llm', 'country', 'aliases']:",
329
- " if col not in df.columns:",
330
- " df[col] = 'Unknown'",
331
- "",
332
- "# Create prompts for all rows (same as DeepSeek)",
333
- "print(\"Creating prompts...\")",
334
- "df['prompt'] = df.apply(create_prompt, axis=1)",
335
- "",
336
- "print(f\"\\nAnnotating with BLOOMZ-7B1 LOCAL - rows {current_index} to {len(df)}...\")",
337
- "print(f\"Model: {MODEL_NAME}\")",
338
- "print(f\"This may take a while...\\n\")",
339
- "",
340
- "try:",
341
- " start_time = time.time()",
342
- "",
343
- " for i in tqdm(range(current_index, len(df)), desc=\"Annotating\"):",
344
- " row = df.iloc[i]",
345
- "",
346
- " # Query BLOOMZ (equivalent to DeepSeek query)",
347
- " response = query_bloomz_local(row['prompt'])",
348
- " parsed_data = parse_response(response)",
349
- "",
350
- " # Log the complete interaction for debugging",
351
- " log_response(",
352
- " idx=i,",
353
- " name=row.get('real_name', row.get('name', 'Unknown')),",
354
- " prompt=row['prompt'],",
355
- " full_prompt=query_bloomz_local.last_full_prompt if hasattr(query_bloomz_local, 'last_full_prompt') else 'N/A',",
356
- " raw_response=response if response else 'None',",
357
- " parsed_data=parsed_data",
358
- " )",
359
- "",
360
- " # Update dataframe",
361
- " for key, value in parsed_data.items():",
362
- " df.at[i, key] = value",
363
- "",
364
- " current_index = i + 1",
365
- "",
366
- " # Save progress at intervals",
367
- " if (i + 1) % SAVE_INTERVAL == 0 or (i + 1) == len(df):",
368
- " df.to_csv(output_file, index=False)",
369
- " with open(index_file, 'w') as f:",
370
- " f.write(str(current_index))",
371
- " print(f\"\u2705 Progress saved after {i+1} rows\")",
372
- "",
373
- " # Optional: Add small delay to prevent overheating (not needed for rate limiting like DeepSeek)",
374
- " # time.sleep(0.1)",
375
- "",
376
- " elapsed_total = time.time() - start_time",
377
- " print(f\"\\n\u2705 Done! Final results saved to {output_file}\")",
378
- "",
379
- " # Summary statistics (same as DeepSeek)",
380
- " print(\"\\n=== Summary Statistics ===\")",
381
- " print(f\"Total processed: {len(df)}\")",
382
- " print(f\"\\nGender distribution:\")",
383
- " print(df['gender'].value_counts())",
384
- " print(f\"\\nTop 10 profession combinations:\")",
385
- " print(df['profession_llm'].value_counts().head(10))",
386
- " print(f\"\\nTop 10 countries:\")",
387
- " print(df['country'].value_counts().head(10))",
388
- "",
389
- " # Sample results",
390
- " print(\"\\n=== Sample Results ===\")",
391
- " display_cols = ['real_name', 'full_name', 'gender', 'profession_llm', 'country']",
392
- " available_cols = [col for col in display_cols if col in df.columns]",
393
- " print(df[available_cols].head(10).to_string(index=False))",
394
- "",
395
- " # Additional info for local model",
396
- " print(f\"\\nTotal time: {elapsed_total/60:.1f} minutes\")",
397
- " print(f\"Average speed: {len(df)/(elapsed_total/3600):.1f} samples/hour\")",
398
- " if torch.cuda.is_available():",
399
- " print(f\"Final VRAM usage: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB\")",
400
- "",
401
- "except Exception as e:",
402
- " print(f\"\u26a0\ufe0f Error encountered: {e}\")",
403
- " print(f\"\u26a0\ufe0f Last processed index: {current_index}\")",
404
- "",
405
- " # Save progress before exiting",
406
- " df.to_csv(output_file, index=False)",
407
- " with open(index_file, 'w') as f:",
408
- " f.write(str(current_index))",
409
- "",
410
- " print(f\"\u26a0\ufe0f Progress saved up to row {current_index}\")",
411
- ""
412
  ]
 
 
 
 
 
 
 
 
413
  }
414
  ],
415
  "metadata": {
@@ -433,4 +347,4 @@
433
  },
434
  "nbformat": 4,
435
  "nbformat_minor": 5
436
- }
 
2
  "cells": [
3
  {
4
  "cell_type": "code",
5
+ "execution_count": 13,
6
  "id": "3b87c378-241e-41ab-be6e-84222594f22f",
7
+ "metadata": {
8
+ "execution": {
9
+ "iopub.execute_input": "2025-11-28T13:07:47.025752Z",
10
+ "iopub.status.busy": "2025-11-28T13:07:47.025552Z",
11
+ "iopub.status.idle": "2025-11-28T13:07:47.128799Z",
12
+ "shell.execute_reply": "2025-11-28T13:07:47.128306Z",
13
+ "shell.execute_reply.started": "2025-11-28T13:07:47.025736Z"
14
+ }
15
+ },
16
  "outputs": [],
17
  "source": [
18
+ "import pandas as pd\n",
19
+ "import json\n",
20
+ "import time\n",
21
+ "import re\n",
22
+ "from pathlib import Path\n",
23
+ "from tqdm import tqdm\n",
24
+ "import torch\n",
25
+ "from transformers import AutoModelForCausalLM, AutoTokenizer\n",
26
+ "from datetime import datetime\n",
27
+ "\n",
28
+ "# Import is used for pd.notna() and pd.isna() checks\n",
29
+ "\n",
30
+ "current_dir = Path.cwd()\n",
31
+ "input_file = current_dir.parent / \"data/CSV/model_adapter/real_person_adapter_step_02_NER.csv\"\n",
32
+ "\n",
33
+ "# === CONFIGURATION ===\n",
34
+ "TEST_MODE = True\n",
35
+ "TEST_SIZE = 10\n",
36
+ "MAX_ROWS = 20000\n",
37
+ "SAVE_INTERVAL = 20\n",
38
+ "\n",
39
+ "# Model settings - BLOOMZ (BigScience - European consortium)\n",
40
+ "MODEL_NAME = \"bigscience/bloomz-7b1\" # Largest instruction-tuned BLOOM model\n",
41
+ "CACHE_DIR = current_dir.parent / \"data/models\"\n",
42
+ "CACHE_DIR.mkdir(parents=True, exist_ok=True)\n",
43
+ "\n",
44
+ "PROFESSION_CATEGORIES = [\n",
45
+ " \"actor\", \"adult performer\", \"singer/musician\", \"model\",\n",
46
+ " \"online personality\", \"public figure\", \"voice actor/ASMR\",\n",
47
+ " \"sports professional\", \"tv personality\"\n",
48
+ "]\n",
49
+ "\n",
50
+ "# === LOAD MODEL ===\n",
51
+ "print(f\"Loading model: {MODEL_NAME}\")\n",
52
+ "print(f\"Cache directory: {CACHE_DIR}\")\n",
53
+ "print(f\"This may take a while on first run (~14GB download)...\\n\")\n",
54
+ "\n",
55
+ "# Check GPU availability\n",
56
+ "device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n",
57
+ "print(f\"Device: {device}\")\n",
58
+ "\n",
59
+ "if device == \"cpu\":\n",
60
+ " print(\"⚠️ WARNING: No GPU detected! Inference will be VERY slow.\")\n",
61
+ " print(\" Consider using a GPU or reducing model size.\")\n",
62
+ "\n",
63
+ "# Load tokenizer\n",
64
+ "print(\"Loading tokenizer...\")\n",
65
+ "try:\n",
66
+ " tokenizer = AutoTokenizer.from_pretrained(\n",
67
+ " MODEL_NAME,\n",
68
+ " cache_dir=str(CACHE_DIR)\n",
69
+ " )\n",
70
+ " print(\"✅ Tokenizer loaded\")\n",
71
+ "except Exception as e:\n",
72
+ " print(f\"❌ Error loading tokenizer: {e}\")\n",
73
+ " raise\n",
74
+ "\n",
75
+ "# Ensure pad token is set\n",
76
+ "if tokenizer.pad_token is None:\n",
77
+ " tokenizer.pad_token = tokenizer.eos_token\n",
78
+ " print(f\"Set pad_token to eos_token: {tokenizer.eos_token}\")\n",
79
+ "\n",
80
+ "# Load model with optimizations\n",
81
+ "print(\"Loading model (this may take several minutes)...\")\n",
82
+ "try:\n",
83
+ " model = AutoModelForCausalLM.from_pretrained(\n",
84
+ " MODEL_NAME,\n",
85
+ " cache_dir=str(CACHE_DIR),\n",
86
+ " torch_dtype=torch.bfloat16, # Use BF16 for efficiency\n",
87
+ " device_map=\"auto\", # Automatically distribute across GPUs\n",
88
+ " low_cpu_mem_usage=True # Optimize memory usage\n",
89
+ " )\n",
90
+ " model.eval() # Set to evaluation mode\n",
91
+ " print(\"✅ Model loaded\")\n",
92
+ "except Exception as e:\n",
93
+ " print(f\"❌ Error loading model: {e}\")\n",
94
+ " raise\n",
95
+ "\n",
96
+ "# Check VRAM usage\n",
97
+ "if torch.cuda.is_available():\n",
98
+ " vram_gb = torch.cuda.max_memory_allocated() / 1024**3\n",
99
+ " print(f\"VRAM used: {vram_gb:.2f} GB\\n\")\n",
100
+ "\n",
101
+ "# === LOAD DATA ===\n",
102
+ "df = pd.read_csv(input_file)\n",
103
+ "print(f\"Loaded {len(df)} rows\")\n",
104
+ "\n",
105
+ "if TEST_MODE:\n",
106
+ " print(f\"Running in TEST MODE with {TEST_SIZE} samples\")\n",
107
+ " df = df.head(TEST_SIZE).copy()\n",
108
+ "elif MAX_ROWS:\n",
109
+ " df = df.head(MAX_ROWS).copy()\n",
110
+ "\n",
111
+ "# === CREATE PROMPT (Exact DeepSeek style) ===\n",
112
+ "# === CREATE PROMPT (BLOOMZ-optimized - Complete format) ===\n",
113
+ "def create_prompt(row):\n",
114
+ " \"\"\"Create prompt optimized for BLOOMZ with complete examples.\"\"\"\n",
115
+ " name = row.get('real_name', row.get('name', ''))\n",
116
+ " if pd.isna(name):\n",
117
+ " name = row.get('name', '')\n",
118
+ "\n",
119
+ " # Gather hints\n",
120
+ " hints = []\n",
121
+ " if pd.notna(row.get('likely_profession')):\n",
122
+ " hints.append(str(row['likely_profession']))\n",
123
+ " if pd.notna(row.get('likely_nationality')):\n",
124
+ " hints.append(str(row['likely_nationality']))\n",
125
+ " if pd.notna(row.get('likely_country')):\n",
126
+ " hints.append(str(row['likely_country']))\n",
127
+ "\n",
128
+ " # Add tags if we don't have enough hints\n",
129
+ " if len(hints) < 3:\n",
130
+ " for i in range(1, 8):\n",
131
+ " tag_col = f'tag_{i}'\n",
132
+ " if tag_col in row and pd.notna(row[tag_col]):\n",
133
+ " tag_val = str(row[tag_col])\n",
134
+ " if tag_val not in hints:\n",
135
+ " hints.append(tag_val)\n",
136
+ " if len(hints) >= 5:\n",
137
+ " break\n",
138
+ "\n",
139
+ " hint_text = \", \".join(hints[:5]) if hints else \"none\"\n",
140
+ "\n",
141
+ " # BLOOMZ needs complete format shown - don't end with \"1.\"\n",
142
+ " return f\"\"\"Task: Extract person information in 5 numbered lines.\n",
143
+ "\n",
144
+ "Format:\n",
145
+ "1. Full legal name\n",
146
+ "2. Stage names/aliases\n",
147
+ "3. Gender\n",
148
+ "4. Professions (from: actor, adult performer, singer/musician, model, online personality, public figure, voice actor/ASMR, sports professional, tv personality)\n",
149
+ "5. Country\n",
150
+ "\n",
151
+ "Example:\n",
152
+ "Person: Taylor Swift (singer, American, pop music)\n",
153
+ "Answer:\n",
154
+ "1. Taylor Alison Swift\n",
155
+ "2. Taylor Swift\n",
156
+ "3. Female\n",
157
+ "4. singer/musician, online personality\n",
158
+ "5. United States\n",
159
+ "\n",
160
+ "Person: {name} ({hint_text})\n",
161
+ "Answer:\n",
162
+ "\"\"\"\n",
163
+ "\n",
164
+ "# === QUERY BLOOMZ LOCAL (Fixed generation parameters) ===\n",
165
+ "def query_bloomz_local(prompt: str) -> str:\n",
166
+ " \"\"\"Query BLOOMZ-7B1 locally via transformers, return raw response string.\"\"\"\n",
167
+ " try:\n",
168
+ " # Store full prompt for logging\n",
169
+ " query_bloomz_local.last_full_prompt = prompt\n",
170
+ "\n",
171
+ " # Tokenize WITHOUT truncation\n",
172
+ " inputs = tokenizer(\n",
173
+ " prompt,\n",
174
+ " return_tensors=\"pt\",\n",
175
+ " truncation=False\n",
176
+ " ).to(device)\n",
177
+ " \n",
178
+ " # Store the input length for proper extraction later\n",
179
+ " input_length = inputs['input_ids'].shape[1]\n",
180
+ "\n",
181
+ " # Generate with parameters optimized for BLOOMZ completion\n",
182
+ " with torch.no_grad():\n",
183
+ " outputs = model.generate(\n",
184
+ " **inputs,\n",
185
+ " max_new_tokens=300, # Increased to allow full completion\n",
186
+ " min_new_tokens=50, # Force minimum generation length\n",
187
+ " temperature=0.5, # Balanced creativity\n",
188
+ " do_sample=True,\n",
189
+ " top_p=0.9,\n",
190
+ " top_k=50,\n",
191
+ " repetition_penalty=1.15,\n",
192
+ " pad_token_id=tokenizer.eos_token_id,\n",
193
+ " eos_token_id=tokenizer.eos_token_id,\n",
194
+ " early_stopping=False, # Changed to False - don't stop early!\n",
195
+ " num_beams=1 # Greedy-like but with sampling\n",
196
+ " )\n",
197
+ "\n",
198
+ " # Extract only the NEW generated tokens\n",
199
+ " generated_ids = outputs[0][input_length:]\n",
200
+ " generated_text = tokenizer.decode(generated_ids, skip_special_tokens=True)\n",
201
+ "\n",
202
+ " # Debug output (show first 5 now to see more patterns)\n",
203
+ " if not hasattr(query_bloomz_local, 'debug_count'):\n",
204
+ " query_bloomz_local.debug_count = 0\n",
205
+ "\n",
206
+ " if query_bloomz_local.debug_count < 5:\n",
207
+ " print(f\"\\n📝 BLOOMZ Debug #{query_bloomz_local.debug_count + 1}:\")\n",
208
+ " print(f\"Prompt tokens: {input_length}\")\n",
209
+ " print(f\"Generated tokens: {len(generated_ids)}\")\n",
210
+ " print(f\"Full generation:\\n{generated_text}\")\n",
211
+ " print(f\"{'='*60}\\n\")\n",
212
+ " query_bloomz_local.debug_count += 1\n",
213
+ "\n",
214
+ " return generated_text.strip()\n",
215
+ "\n",
216
+ " except Exception as e:\n",
217
+ " print(f\"Error querying BLOOMZ: {e}\")\n",
218
+ " import traceback\n",
219
+ " traceback.print_exc()\n",
220
+ " query_bloomz_local.last_full_prompt = f\"ERROR: {e}\"\n",
221
+ " return None\n",
222
+ "\n",
223
+ " \n",
224
+ "# === PROCESS ===\n",
225
+ "output_file = current_dir.parent / f\"data/CSV/bloomz_annotated_POI{'_test' if TEST_MODE else ''}.csv\"\n",
226
+ "index_file = current_dir.parent / \"misc/bloomz_query_index.txt\"\n",
227
+ "\n",
228
+ "current_index = 0\n",
229
+ "if index_file.exists():\n",
230
+ " with open(index_file) as f:\n",
231
+ " current_index = int(f.read().strip())\n",
232
+ " print(f\"Resuming from index {current_index}\")\n",
233
+ "\n",
234
+ "# Initialize columns (same as DeepSeek)\n",
235
+ "for col in ['full_name', 'gender', 'profession_llm', 'country', 'aliases']:\n",
236
+ " if col not in df.columns:\n",
237
+ " df[col] = 'Unknown'\n",
238
+ "\n",
239
+ "# Create prompts for all rows (same as DeepSeek)\n",
240
+ "print(\"Creating prompts...\")\n",
241
+ "df['prompt'] = df.apply(create_prompt, axis=1)\n",
242
+ "\n",
243
+ "print(f\"\\nAnnotating with BLOOMZ-7B1 LOCAL - rows {current_index} to {len(df)}...\")\n",
244
+ "print(f\"Model: {MODEL_NAME}\")\n",
245
+ "print(f\"This may take a while...\\n\")\n",
246
+ "\n",
247
+ "try:\n",
248
+ " start_time = time.time()\n",
249
+ "\n",
250
+ " for i in tqdm(range(current_index, len(df)), desc=\"Annotating\"):\n",
251
+ " row = df.iloc[i]\n",
252
+ "\n",
253
+ " # Query BLOOMZ (equivalent to DeepSeek query)\n",
254
+ " response = query_bloomz_local(row['prompt'])\n",
255
+ " parsed_data = parse_response(response)\n",
256
+ "\n",
257
+ " # Log the complete interaction for debugging\n",
258
+ " log_response(\n",
259
+ " idx=i,\n",
260
+ " name=row.get('real_name', row.get('name', 'Unknown')),\n",
261
+ " prompt=row['prompt'],\n",
262
+ " full_prompt=query_bloomz_local.last_full_prompt if hasattr(query_bloomz_local, 'last_full_prompt') else 'N/A',\n",
263
+ " raw_response=response if response else 'None',\n",
264
+ " parsed_data=parsed_data\n",
265
+ " )\n",
266
+ "\n",
267
+ " # Update dataframe\n",
268
+ " for key, value in parsed_data.items():\n",
269
+ " df.at[i, key] = value\n",
270
+ "\n",
271
+ " current_index = i + 1\n",
272
+ "\n",
273
+ " # Save progress at intervals\n",
274
+ " if (i + 1) % SAVE_INTERVAL == 0 or (i + 1) == len(df):\n",
275
+ " df.to_csv(output_file, index=False)\n",
276
+ " with open(index_file, 'w') as f:\n",
277
+ " f.write(str(current_index))\n",
278
+ " print(f\"✅ Progress saved after {i+1} rows\")\n",
279
+ "\n",
280
+ " # Optional: Add small delay to prevent overheating (not needed for rate limiting like DeepSeek)\n",
281
+ " # time.sleep(0.1)\n",
282
+ "\n",
283
+ " elapsed_total = time.time() - start_time\n",
284
+ " print(f\"\\n✅ Done! Final results saved to {output_file}\")\n",
285
+ "\n",
286
+ " # Summary statistics (same as DeepSeek)\n",
287
+ " print(\"\\n=== Summary Statistics ===\")\n",
288
+ " print(f\"Total processed: {len(df)}\")\n",
289
+ " print(f\"\\nGender distribution:\")\n",
290
+ " print(df['gender'].value_counts())\n",
291
+ " print(f\"\\nTop 10 profession combinations:\")\n",
292
+ " print(df['profession_llm'].value_counts().head(10))\n",
293
+ " print(f\"\\nTop 10 countries:\")\n",
294
+ " print(df['country'].value_counts().head(10))\n",
295
+ "\n",
296
+ " # Sample results\n",
297
+ " print(\"\\n=== Sample Results ===\")\n",
298
+ " display_cols = ['real_name', 'full_name', 'gender', 'profession_llm', 'country']\n",
299
+ " available_cols = [col for col in display_cols if col in df.columns]\n",
300
+ " print(df[available_cols].head(10).to_string(index=False))\n",
301
+ "\n",
302
+ " # Additional info for local model\n",
303
+ " print(f\"\\nTotal time: {elapsed_total/60:.1f} minutes\")\n",
304
+ " print(f\"Average speed: {len(df)/(elapsed_total/3600):.1f} samples/hour\")\n",
305
+ " if torch.cuda.is_available():\n",
306
+ " print(f\"Final VRAM usage: {torch.cuda.max_memory_allocated() / 1024**3:.2f} GB\")\n",
307
+ "\n",
308
+ "except Exception as e:\n",
309
+ " print(f\"⚠️ Error encountered: {e}\")\n",
310
+ " print(f\"⚠️ Last processed index: {current_index}\")\n",
311
+ "\n",
312
+ " # Save progress before exiting\n",
313
+ " df.to_csv(output_file, index=False)\n",
314
+ " with open(index_file, 'w') as f:\n",
315
+ " f.write(str(current_index))\n",
316
+ "\n",
317
+ " print(f\"⚠️ Progress saved up to row {current_index}\")\n"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
318
  ]
319
+ },
320
+ {
321
+ "cell_type": "code",
322
+ "execution_count": null,
323
+ "id": "c458d50f-0cb3-421e-99ab-62795f88242c",
324
+ "metadata": {},
325
+ "outputs": [],
326
+ "source": []
327
  }
328
  ],
329
  "metadata": {
 
347
  },
348
  "nbformat": 4,
349
  "nbformat_minor": 5
350
+ }
jupyter_notebooks/Section_2-3-4_Figure_8_deepfake_adapters.ipynb CHANGED
The diff for this file is too large to render. See raw diff
 
jupyter_notebooks/Section_2-3_Figure_5_co-occurence_promotional_tags.ipynb CHANGED
@@ -292,7 +292,7 @@
292
  ],
293
  "metadata": {
294
  "kernelspec": {
295
- "display_name": "latm",
296
  "language": "python",
297
  "name": "python3"
298
  },
@@ -306,9 +306,9 @@
306
  "name": "python",
307
  "nbconvert_exporter": "python",
308
  "pygments_lexer": "ipython3",
309
- "version": "3.10.15"
310
  }
311
  },
312
  "nbformat": 4,
313
- "nbformat_minor": 2
314
  }
 
292
  ],
293
  "metadata": {
294
  "kernelspec": {
295
+ "display_name": "Python 3 (ipykernel)",
296
  "language": "python",
297
  "name": "python3"
298
  },
 
306
  "name": "python",
307
  "nbconvert_exporter": "python",
308
  "pygments_lexer": "ipython3",
309
+ "version": "3.12.10"
310
  }
311
  },
312
  "nbformat": 4,
313
+ "nbformat_minor": 4
314
  }
misc/bloomz_query_index.txt DELETED
@@ -1 +0,0 @@
1
- 10
 
 
misc/query_indicies/deepseek_query_index.txt DELETED
@@ -1 +0,0 @@
1
- 10
 
 
misc/query_indicies/mistral_local_query_index.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ 8790