File size: 58,541 Bytes
c7a6fe6 | 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 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 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 | {
"cells": [
{
"cell_type": "markdown",
"id": "d847270d",
"metadata": {},
"source": [
"## Step 0: Prepare Your Dataset"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "44047dbb",
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"\n",
"# 1. Load the datasets\n",
"with open(\"/home/mshahidul/readctrl/data/final_result/consolidated_ratings_edit.json\", 'r') as f:\n",
" ratings_data = json.load(f)\n",
"ratings_data=ratings_data[7:]\n",
"with open(\"/home/mshahidul/readctrl/data/extracting_subclaim/extracted_subclaims_syn_data_with_gs_summary_en.json\", 'r') as f:\n",
" text_data = json.load(f)\n",
"\n",
"# 2. Updated mapping: Store the whole item or specific keys for fulltext and summary\n",
"# We map the index to a dictionary containing the variations and the original full text/summary\n",
"text_map = {\n",
" item['index']: {\n",
" 'variations': item['diff_label_texts'],\n",
" 'fulltext': item.get('fulltext', \"\"),\n",
" 'summary': item.get('summary', \"\")\n",
" } \n",
" for item in text_data\n",
"}\n",
"\n",
"cleaned_data = []\n",
"\n",
"# 3. Iterate through ratings and extract data\n",
"for entry in ratings_data:\n",
" doc_id = entry['doc_id']\n",
" label = entry['health_literacy_label']\n",
" \n",
" if doc_id in text_map:\n",
" source_info = text_map[doc_id]\n",
" \n",
" # Retrieve the specific text version based on the label\n",
" # .get() handles cases where a specific label might be missing\n",
" labeled_text = source_info['variations'].get(label, \"\")\n",
" \n",
" # Construct the expanded object\n",
" cleaned_data.append({\n",
" \"doc_id\": doc_id,\n",
" \"label\": label,\n",
" \"gen_text\": labeled_text,\n",
" \"fulltext\": source_info['fulltext'],\n",
" \"gs_summary\": source_info['summary']\n",
" })\n",
"\n",
"# 4. Output the clean JSON\n",
"output_path = \"/home/mshahidul/readctrl/data/new_exp/cleaned_health_literacy_data.json\"\n",
"with open(output_path, 'w') as f:\n",
" json.dump(cleaned_data, f, indent=4, ensure_ascii=False)\n",
"\n",
"print(f\"Successfully processed {len(cleaned_data)} examples.\")"
]
},
{
"cell_type": "markdown",
"id": "a1e6b0ae",
"metadata": {},
"source": [
"## Step 1: Pick Few-Shot Examples"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "71e83ac8",
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"import requests\n",
"from collections import defaultdict\n",
"\n",
"# Configuration\n",
"API_URL = \"http://172.16.34.29:8004/v1/chat/completions\"\n",
"MODEL_NAME = \"Qwen/Qwen3-30B-A3B-Instruct-2507\"\n",
"INPUT_FILE = \"/home/mshahidul/readctrl/data/new_exp/cleaned_health_literacy_data.json\"\n",
"OUTPUT_FILE = \"/home/mshahidul/readctrl/data/new_exp/few_shot_examples.json\"\n",
"\n",
"def get_text_metadata(text):\n",
" \"\"\"Ask the LLM to identify the topic and medical complexity of a text.\"\"\"\n",
" prompt = f\"\"\"Analyze the following medical text and provide a 1-word topic (e.g., Cardiology, Nutrition, Medication) and a 1-word complexity level (Simple, Moderate, Technical).\n",
" Text: {text}...\n",
" Format: Topic | Complexity\"\"\"\n",
" \n",
" try:\n",
" response = requests.post(API_URL, json={\n",
" \"model\": MODEL_NAME,\n",
" \"messages\": [{\"role\": \"user\", \"content\": prompt}],\n",
" \"temperature\": 0.1\n",
" })\n",
" return response.json()['choices'][0]['message']['content'].strip()\n",
" except:\n",
" return \"General | Unknown\"\n",
"\n",
"# 1. Load the cleaned data\n",
"with open(INPUT_FILE, 'r') as f:\n",
" data = json.load(f)\n",
"\n",
"# 2. Group data by label\n",
"grouped_data = defaultdict(list)\n",
"for item in data:\n",
" grouped_data[item['label']].append(item)\n",
"\n",
"# 3. Select diverse examples for each label\n",
"few_shot_selection = {}\n",
"\n",
"for label, examples in grouped_data.items():\n",
" print(f\"Processing label: {label}...\")\n",
" \n",
" # Analyze a subset (or all) to find diversity\n",
" scored_examples = []\n",
" for ex in examples: \n",
" metadata = get_text_metadata(ex['gen_text'])\n",
" ex['metadata'] = metadata\n",
" scored_examples.append(ex)\n",
" \n",
" # Heuristic: Sort by metadata to group similar topics, then pick spread-out indices\n",
" scored_examples.sort(key=lambda x: x['metadata'])\n",
" \n",
" # Pick 5 examples spread across the sorted metadata for maximum diversity\n",
" step = max(1, len(scored_examples) // 5)\n",
" selected = scored_examples[::step][:5]\n",
" few_shot_selection[label] = selected\n",
"\n",
"# 4. Save the result\n",
"with open(OUTPUT_FILE, 'w') as f:\n",
" json.dump(few_shot_selection, f, indent=4)\n",
"\n",
"print(f\"Few-shot examples saved to: {OUTPUT_FILE}\")"
]
},
{
"cell_type": "markdown",
"id": "d48720a6",
"metadata": {},
"source": [
"## Step 2: Decide on LLM(s)"
]
},
{
"cell_type": "markdown",
"id": "74b07429",
"metadata": {},
"source": [
"## V2"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "912f3d85",
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"import requests\n",
"from openai import OpenAI\n",
"\n",
"# --- Configuration ---\n",
"LOCAL_API_URL = \"http://172.16.34.29:8004/v1/chat/completions\"\n",
"LOCAL_MODEL_NAME = \"Qwen/Qwen3-30B-A3B-Instruct-2507\"\n",
"\n",
"api_file = \"/home/mshahidul/api_new.json\"\n",
"with open(api_file, \"r\") as f:\n",
" api_keys = json.load(f)\n",
"\n",
"openai_client = OpenAI(api_key=api_keys[\"openai\"])\n",
"OPENAI_MODEL_NAME = \"gpt-5\" # Note: Ensure your model version is correct\n",
"\n",
"FEW_SHOT_FILE = \"/home/mshahidul/readctrl/data/new_exp/few_shot_examples.json\"\n",
"OUTPUT_PATH = \"/home/mshahidul/readctrl/data/new_exp/final_prompt_template.txt\"\n",
"\n",
"# --- Logic ---\n",
"\n",
"def get_reasoning(fulltext, gen_text, label, provider=\"local\"):\n",
" \"\"\"\n",
" Ask an LLM to explain why the text fits the label in JSON format.\n",
" \"\"\"\n",
" # Explicitly asking for JSON in the prompt\n",
" prompt = f\"\"\"Compare the 'Target Text' to the 'Original Fulltext'. \n",
"Explain why the Target Text fits the health literacy label: {label}.\n",
"Focus on how vocabulary, jargon, and sentence structure were adapted.\n",
"\n",
"Original Fulltext: {fulltext}\n",
"Target Text: {gen_text}\n",
"Label: {label}\n",
"\n",
"Return your response ONLY as a JSON object with the following key:\n",
"\"reasoning\": \"your 1-2 sentence explanation\"\n",
"\"\"\"\n",
"\n",
" try:\n",
" if provider == \"openai\":\n",
" response = openai_client.chat.completions.create(\n",
" model=OPENAI_MODEL_NAME,\n",
" messages=[{\"role\": \"user\", \"content\": prompt}],\n",
" response_format={ \"type\": \"json_object\" } # Force JSON for OpenAI\n",
" )\n",
" content = response.choices[0].message.content.strip()\n",
" else:\n",
" response = requests.post(LOCAL_API_URL, json={\n",
" \"model\": LOCAL_MODEL_NAME,\n",
" \"messages\": [{\"role\": \"user\", \"content\": prompt}],\n",
" \"temperature\": 0\n",
" })\n",
" content = response.json()['choices'][0]['message']['content'].strip()\n",
" \n",
" # Parse JSON and extract reasoning\n",
" data = json.loads(content)\n",
" return data.get(\"reasoning\", \"Reasoning key not found.\")\n",
" \n",
" except Exception as e:\n",
" print(f\"Error with {provider}: {e}\")\n",
" return \"Reasoning could not be generated.\"\n",
"\n",
"# 1. Load the selected examples\n",
"with open(FEW_SHOT_FILE, 'r') as f:\n",
" few_shot_data = json.load(f)\n",
"\n",
"# 2. Build the few-shot string\n",
"few_shot_string = \"\"\n",
"REASONING_PROVIDER = \"openai\" \n",
"\n",
"print(f\"Generating reasoning using: {REASONING_PROVIDER}...\")\n",
"info=[]\n",
"for label in [\"low_health_literacy\", \"intermediate_health_literacy\", \"proficient_health_literacy\"]:\n",
" examples = few_shot_data.get(label, [])\n",
" for ex in examples:\n",
" reason = get_reasoning(ex.get('fulltext', \"\"), ex['gen_text'], label, provider=REASONING_PROVIDER)\n",
" \n",
" # Adding structured few-shot examples to the string\n",
" few_shot_string += f\"Original Fulltext: \\\"{ex.get('fulltext', '')}\\\"\\n\"\n",
" few_shot_string += f\"Target Text: \\\"{ex['gen_text']}\\\"\\n\"\n",
" few_shot_string += f\"Reasoning: {reason}\\n\"\n",
" few_shot_string += f\"Label: {label}\\n\"\n",
" few_shot_string += \"-\" * 30 + \"\\n\"\n",
" info.append({\n",
" \"doc_id\": ex.get('doc_id', \"\"),\n",
" \"fulltext\": ex.get('fulltext', \"\"),\n",
" \"gen_text\": ex['gen_text'],\n",
" \"reasoning\": reason,\n",
" \"label\": label\n",
" }) \n",
"\n",
"# 3. Define the Final Prompt Structure\n",
"instruction = \"\"\"You are an expert in health communication. Your task is to judge the health literacy level of a target text based on its original medical source.\n",
"\n",
"Classify the text into one of three categories:\n",
"1. low_health_literacy: Uses common words (everyday language), very short sentences, and eliminates all medical jargon.\n",
"2. intermediate_health_literacy: Uses some medical terms with explanation, standard sentence length, requires basic health knowledge.\n",
"3. proficient_health_literacy: Uses high-level medical jargon, technical language, and academic or professional structures.\n",
"\n",
"### Few-Shot Examples:\n",
"\"\"\"\n",
"\n",
"# 4. Final Template Construction\n",
"final_prompt_template = (\n",
" instruction + \n",
" few_shot_string + \n",
" \"\\n### Now judge this text:\\n\"\n",
" \"Original Fulltext: \\\"{fulltext}\\\"\\n\"\n",
" \"Target Text: \\\"{input_text}\\\"\\n\"\n",
" \"Reasoning:\"\n",
")\n",
"\n",
"with open(OUTPUT_PATH, 'w') as f:\n",
" f.write(final_prompt_template)\n",
"with open(OUTPUT_PATH.replace('.txt', '_info.json'), 'w') as f:\n",
" json.dump(info, f, indent=4)\n",
"print(f\"Structured prompt template saved to {OUTPUT_PATH}\")"
]
},
{
"cell_type": "markdown",
"id": "8c470dd5",
"metadata": {},
"source": [
"## Fewshot data selection"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "06158d8d",
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"import os\n",
"\n",
"# --- Configuration ---\n",
"# Path to your existing data (containing 'reasoning', 'gen_text', and 'label')\n",
"INPUT_INFO_FILE = \"/home/mshahidul/readctrl/data/new_exp/final_prompt_template_info.json\"\n",
"OUTPUT_PATH = \"/home/mshahidul/readctrl/data/new_exp/new_prompt_template.txt\"\n",
"\n",
"# Decide how many few-shot examples you want to include for each label\n",
"FEW_SHOT_PER_LABEL = 2 # Change this to 1, 3, etc.\n",
"\n",
"# --- Logic ---\n",
"\n",
"def generate_prompt_from_json(input_json_path, num_per_label):\n",
" if not os.path.exists(input_json_path):\n",
" return f\"Error: File {input_json_path} not found. Please check the path.\"\n",
" \n",
" with open(input_json_path, 'r') as f:\n",
" data = json.load(f)\n",
" \n",
" # Organize the data by label to ensure even distribution\n",
" labeled_data = {}\n",
" for entry in data:\n",
" label = entry['label']\n",
" if label not in labeled_data:\n",
" labeled_data[label] = []\n",
" labeled_data[label].append(entry)\n",
" \n",
" # Build the few-shot section\n",
" few_shot_string = \"\"\n",
" # Define labels in a logical order\n",
" target_labels = [\"low_health_literacy\", \"intermediate_health_literacy\", \"proficient_health_literacy\"]\n",
" \n",
" for label in target_labels:\n",
" examples = labeled_data.get(label, [])\n",
" # Slice the list based on your variable\n",
" selected_examples = examples[:num_per_label]\n",
" \n",
" for ex in selected_examples:\n",
" # Construct the example block WITHOUT the fulltext\n",
" few_shot_string += f\"Target Text: \\\"{ex['gen_text']}\\\"\\n\"\n",
" few_shot_string += f\"Reasoning: {ex['reasoning']}\\n\"\n",
" few_shot_string += f\"Label: {label}\\n\"\n",
" few_shot_string += \"-\" * 30 + \"\\n\"\n",
"\n",
" # Define the final instruction structure (no mention of fulltext comparison)\n",
" instruction = \"\"\"You are an expert in health communication. Your task is to judge the health literacy level of the provided text.\n",
"\n",
"Classify the text into one of three categories:\n",
"1. low_health_literacy: Uses common words (everyday language), very short sentences, and avoids medical jargon.\n",
"2. intermediate_health_literacy: Uses some medical terms with explanation, standard sentence length, requires basic health knowledge.\n",
"3. proficient_health_literacy: Uses high-level medical jargon, technical language, and academic or professional structures.\n",
"\n",
"### Examples:\n",
"\"\"\"\n",
"\n",
" # Final Template Construction\n",
" final_template = (\n",
" instruction + \n",
" few_shot_string + \n",
" \"\\n### Task:\\n\"\n",
" \"Target Text: \\\"{input_text}\\\"\\n\"\n",
" \"Reasoning:\"\n",
" )\n",
" \n",
" return final_template\n",
"\n",
"# 1. Generate the string\n",
"new_prompt_template = generate_prompt_from_json(INPUT_INFO_FILE, FEW_SHOT_PER_LABEL)\n",
"\n",
"# 2. Save to file\n",
"with open(OUTPUT_PATH, 'w') as f:\n",
" f.write(new_prompt_template)\n",
"\n",
"print(f\"Successfully created a prompt with {FEW_SHOT_PER_LABEL} examples per label.\")\n",
"print(f\"Saved to: {OUTPUT_PATH}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f78d4619",
"metadata": {},
"outputs": [],
"source": [
"\n",
"with open(\"/home/mshahidul/readctrl/data/new_exp/cleaned_health_literacy_data.json\", 'r') as f:\n",
" cleaned_data = json.load(f)\n",
"with open(\"/home/mshahidul/readctrl/data/new_exp/few_shot_examples.json\", 'r') as f:\n",
" few_shot_examples = json.load(f)\n",
"\n",
"list_data = []\n",
"for item in few_shot_examples:\n",
" for ex in few_shot_examples[item]:\n",
" list_data.append((ex['doc_id'], ex['label']))\n",
"\n",
"test_set = []\n",
"for item in cleaned_data:\n",
" if (item['doc_id'], item['label']) not in list_data:\n",
" test_set.append(item)\n",
"with open(\"/home/mshahidul/readctrl/data/new_exp/test_health_literacy_data.json\", 'w') as f:\n",
" json.dump(test_set, f, indent=4)"
]
},
{
"cell_type": "markdown",
"id": "0531d7c3",
"metadata": {},
"source": [
"## Testing V2"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "ab8b4c96",
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"import requests\n",
"import os\n",
"\n",
"# --- Configuration ---\n",
"DEV_SET_PATH = \"/home/mshahidul/readctrl/data/new_exp/test_health_literacy_data.json\"\n",
"FEW_SHOT_SET_PATH = \"/home/mshahidul/readctrl/data/new_exp/final_prompt_template_info.json\" # Using the one with reasoning\n",
"LOCAL_API_URL = \"http://172.16.34.29:8004/v1/chat/completions\"\n",
"LOCAL_MODEL_NAME = \"Qwen/Qwen3-30B-A3B-Instruct-2507\"\n",
"\n",
"# Define the range of few-shots per label you want to test\n",
"# e.g., [0, 1, 2, 3] will test 0-shot, 1-shot (3 total), 2-shot (6 total), etc.\n",
"SHOTS_TO_EVALUATE = [0, 1, 2, 3]\n",
"\n",
"# --- Core Functions ---\n",
"\n",
"def build_dynamic_prompt(few_shot_data, k_per_label):\n",
" \"\"\"Constructs a prompt with k examples per literacy category.\"\"\"\n",
" instruction = (\n",
" \"You are an expert in health communication. Your task is to judge the health literacy level of the provided text.\\n\"\n",
" \"Classify the text into: low_health_literacy, intermediate_health_literacy, or proficient_health_literacy.\\n\\n\"\n",
" )\n",
" \n",
" if k_per_label == 0:\n",
" return instruction + \"### Task:\\nTarget Text: \\\"{input_text}\\\"\\nReasoning:\"\n",
"\n",
" # Organize few-shot data by label\n",
" categorized = {}\n",
" for entry in few_shot_data:\n",
" label = entry['label']\n",
" categorized.setdefault(label, []).append(entry)\n",
"\n",
" few_shot_blocks = \"### Examples:\\n\"\n",
" labels = [\"low_health_literacy\", \"intermediate_health_literacy\", \"proficient_health_literacy\"]\n",
" \n",
" for label in labels:\n",
" examples = categorized.get(label, [])[:k_per_label]\n",
" for ex in examples:\n",
" few_shot_blocks += f\"Target Text: \\\"{ex['gen_text']}\\\"\\n\"\n",
" few_shot_blocks += f\"Reasoning: {ex['reasoning']}\\n\"\n",
" few_shot_blocks += f\"Label: {label}\\n\"\n",
" few_shot_blocks += \"-\" * 30 + \"\\n\"\n",
" \n",
" return instruction + few_shot_blocks + \"\\n### Task:\\nTarget Text: \\\"{input_text}\\\"\\nReasoning:\"\n",
"\n",
"def get_prediction(prompt_template, input_text):\n",
" \"\"\"Sends the formatted prompt to the local LLM.\"\"\"\n",
" final_prompt = prompt_template.format(input_text=input_text)\n",
" payload = {\n",
" \"model\": LOCAL_MODEL_NAME,\n",
" \"messages\": [{\"role\": \"user\", \"content\": final_prompt}],\n",
" \"temperature\": 0 \n",
" }\n",
" try:\n",
" response = requests.post(LOCAL_API_URL, json=payload, timeout=30)\n",
" return response.json()['choices'][0]['message']['content'].strip()\n",
" except Exception:\n",
" return \"Error\"\n",
"\n",
"def parse_label(text):\n",
" \"\"\"Normalizes LLM output to match dataset labels.\"\"\"\n",
" text = text.lower()\n",
" if \"low\" in text: return \"low_health_literacy\"\n",
" if \"intermediate\" in text: return \"intermediate_health_literacy\"\n",
" if \"proficient\" in text: return \"proficient_health_literacy\"\n",
" return \"unknown\"\n",
"\n",
"# --- Main Execution ---\n",
"\n",
"# 1. Load Data\n",
"with open(DEV_SET_PATH, 'r') as f:\n",
" dev_set = json.load(f)\n",
"with open(FEW_SHOT_SET_PATH, 'r') as f:\n",
" few_shot_pool = json.load(f)\n",
"\n",
"# 2. Filter Dev Set\n",
"# Ensure no overlap between few-shot examples and dev set\n",
"shot_ids = {item['doc_id'] for item in few_shot_pool}\n",
"clean_dev_set = [item for item in dev_set if item['doc_id'] not in shot_ids]\n",
"\n",
"results_summary = []\n",
"\n",
"print(f\"Starting Evaluation on {len(clean_dev_set)} samples...\\n\")\n",
"\n",
"# 3. Loop through shot counts\n",
"for k in SHOTS_TO_EVALUATE:\n",
" print(f\"Evaluating {k}-shot per label (Total {k*3} examples)...\")\n",
" \n",
" current_template = build_dynamic_prompt(few_shot_pool, k)\n",
" correct = 0\n",
" \n",
" for case in clean_dev_set:\n",
" raw_output = get_prediction(current_template, case['gen_text'])\n",
" pred = parse_label(raw_output)\n",
" actual = parse_label(case['label'])\n",
" \n",
" if pred == actual:\n",
" correct += 1\n",
" \n",
" accuracy = (correct / len(clean_dev_set)) * 100\n",
" results_summary.append({\"shots_per_label\": k, \"accuracy\": accuracy})\n",
" print(f\"-> Accuracy: {accuracy:.2f}%\\n\")\n",
"\n",
"# --- Final Report ---\n",
"print(\"-\" * 30)\n",
"print(f\"{'Shots/Label':<15} | {'Accuracy':<10}\")\n",
"print(\"-\" * 30)\n",
"for res in results_summary:\n",
" print(f\"{res['shots_per_label']:<15} | {res['accuracy']:.2f}%\")"
]
},
{
"cell_type": "markdown",
"id": "d5cd799a",
"metadata": {},
"source": [
"## Step 3: Design Initial Prompt using dspy"
]
},
{
"cell_type": "markdown",
"id": "06a0eb62",
"metadata": {},
"source": [
"## V2"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e3529bb0",
"metadata": {},
"outputs": [],
"source": [
"import dspy\n",
"import json\n",
"from typing import Literal\n",
"from dspy.teleprompt import BootstrapFewShotWithRandomSearch\n",
"from dspy.evaluate import Evaluate\n",
"\n",
"# --- 1. LLM Configuration ---\n",
"api_file = \"/home/mshahidul/api_new.json\"\n",
"with open(api_file, \"r\") as f:\n",
" api_keys = json.load(f)\n",
"openai_api_key = api_keys[\"openai\"]\n",
"\n",
"# Student: Local vLLM (Deployment Model)\n",
"vllm_model = dspy.LM(\n",
" model='openai/Qwen/Qwen3-30B-A3B-Instruct-2507',\n",
" api_base=\"http://172.16.34.29:8004/v1\",\n",
" api_key=\"EMPTY\",\n",
" temperature=0.0\n",
")\n",
"\n",
"# Teacher: OpenAI (High-quality rationale generation)\n",
"# Note: Ensure 'gpt-5' is the correct model name in your environment (usually 'gpt-4-turbo' or 'gpt-4o')\n",
"openai_model_teacher = dspy.LM(model='gpt-5', api_key=openai_api_key)\n",
"openai_model_student = dspy.LM(model='gpt-5-mini', api_key=openai_api_key)\n",
"\n",
"dspy.configure(lm=openai_model_student) # Default to OpenAI for optimization\n",
"\n",
"# --- 2. Data Processing & Deduplication ---\n",
"\n",
"# 2.1 Load Training Data (Few-Shot)\n",
"with open(\"/home/mshahidul/readctrl/data/new_exp/few_shot_examples_manual_edit.json\", 'r') as f:\n",
" few_shot_data = json.load(f)\n",
"\n",
"trainset = []\n",
"train_identifiers = set()\n",
"\n",
"for label_key, examples in few_shot_data.items():\n",
" for ex in examples:\n",
" # Create a unique ID to prevent data leakage\n",
" unique_id = f\"{ex['doc_id']}_{label_key}\"\n",
" train_identifiers.add(unique_id)\n",
" \n",
" # In few_shot, 'gen_text' is the summary we want to judge\n",
" trainset.append(dspy.Example(\n",
" summary_text=ex['gen_text'], \n",
" label=label_key\n",
" ).with_inputs('summary_text'))\n",
"\n",
"# 2.2 Load Test Data as Dev Set (Updated Path)\n",
"test_data_path = \"/home/mshahidul/readctrl/data/new_exp/test_health_literacy_data_manual_edit.json\"\n",
"with open(test_data_path, 'r') as f:\n",
" test_data = json.load(f)\n",
"\n",
"devset = []\n",
"for item in test_data:\n",
" unique_id = f\"{item['doc_id']}_{item['label']}\"\n",
" \n",
" # Filter out examples if they accidentally appear in the training set\n",
" if unique_id not in train_identifiers:\n",
" devset.append(dspy.Example(\n",
" summary_text=item['gen_text'], \n",
" label=item['label']\n",
" ).with_inputs('summary_text'))\n",
"\n",
"print(f\"Dataset Stats: Train={len(trainset)}, Dev (Test Set)={len(devset)}\")\n",
"\n",
"# --- 3. Robust Signature & Module ---\n",
"\n",
"class HealthLiteracySignature(dspy.Signature):\n",
" \"\"\"\n",
" Judge the health literacy level of a generated medical summary.\n",
" Identify if the language is suitable for a layperson (low) or requires medical expertise (proficient).\n",
" \"\"\"\n",
" summary_text: str = dspy.InputField(desc=\"The generated medical summary to be analyzed.\")\n",
" reasoning: str = dspy.OutputField(desc=\"Analysis of jargon, acronyms, and sentence complexity.\")\n",
" label: Literal[\"low_health_literacy\", \"intermediate_health_literacy\", \"proficient_health_literacy\"] = dspy.OutputField()\n",
"\n",
"class HealthLiteracyClassifier(dspy.Module):\n",
" def __init__(self):\n",
" super().__init__()\n",
" self.predictor = dspy.ChainOfThought(HealthLiteracySignature)\n",
"\n",
" def forward(self, summary_text):\n",
" return self.predictor(summary_text=summary_text)\n",
"\n",
"# --- 4. Metric and Optimization ---\n",
"\n",
"def health_literacy_metric(gold, pred, trace=None):\n",
" if not pred or not pred.label: return False\n",
" return gold.label.strip().lower() == pred.label.strip().lower()\n",
"\n",
"optimizer = BootstrapFewShotWithRandomSearch(\n",
" metric=health_literacy_metric,\n",
" max_bootstrapped_demos=3,\n",
" num_candidate_programs=8, \n",
" teacher_settings=dict(lm=openai_model_teacher)\n",
")\n",
"\n",
"# Compile the program\n",
"optimized_program = optimizer.compile(HealthLiteracyClassifier(), trainset=trainset)\n",
"\n",
"# --- 5. Evaluation & Saving ---\n",
"\n",
"# Evaluate on the provided test dataset\n",
"evaluator = Evaluate(devset=devset, metric=health_literacy_metric, num_threads=1, display_progress=True)\n",
"accuracy_score = evaluator(optimized_program)\n",
"\n",
"print(f\"\\nOptimization Complete.\") \n",
"print(f\"Final Accuracy on Test Set: {accuracy_score}%\")\n",
"\n",
"# Save the finalized prompt logic\n",
"optimized_program.save(\"/home/mshahidul/readctrl/data/new_exp/optimized_health_classifier_gpt5-mini_v2.json\")"
]
},
{
"cell_type": "markdown",
"id": "10f0396a",
"metadata": {},
"source": [
"## V2 (gen text with src text) not good"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "298dba97",
"metadata": {},
"outputs": [],
"source": [
"import dspy\n",
"import json\n",
"from typing import Literal\n",
"from dspy.teleprompt import BootstrapFewShotWithRandomSearch\n",
"from dspy.evaluate import Evaluate\n",
"\n",
"# --- 1. LLM Configuration ---\n",
"# (Keeping your existing setup)\n",
"api_file = \"/home/mshahidul/api_new.json\"\n",
"with open(api_file, \"r\") as f:\n",
" api_keys = json.load(f)\n",
"openai_api_key = api_keys[\"openai\"]\n",
"\n",
"vllm_model = dspy.LM(\n",
" model='openai/Qwen/Qwen3-30B-A3B-Instruct-2507',\n",
" api_base=\"http://172.16.34.29:8004/v1\",\n",
" api_key=\"EMPTY\",\n",
" temperature=0.0\n",
")\n",
"\n",
"openai_model_teacher = dspy.LM(model='gpt-5', api_key=openai_api_key)\n",
"openai_model_student = dspy.LM(model='gpt-5-mini', api_key=openai_api_key)\n",
"\n",
"dspy.configure(lm=openai_model_student)\n",
"\n",
"# --- 2. Data Processing & Deduplication (Updated for Source Text) ---\n",
"\n",
"# 2.1 Load Training Data\n",
"with open(\"/home/mshahidul/readctrl/data/new_exp/few_shot_examples_manual_edit.json\", 'r') as f:\n",
" few_shot_data = json.load(f)\n",
"\n",
"trainset = []\n",
"train_identifiers = set()\n",
"\n",
"for label_key, examples in few_shot_data.items():\n",
" for ex in examples:\n",
" unique_id = f\"{ex['doc_id']}_{label_key}\"\n",
" train_identifiers.add(unique_id)\n",
" \n",
" # Adding 'source_text' (assumed key is 'fulltext' based on your comment)\n",
" trainset.append(dspy.Example(\n",
" source_text=ex.get('fulltext', \"\"), \n",
" summary_text=ex['gen_text'], \n",
" label=label_key\n",
" ).with_inputs('source_text', 'summary_text'))\n",
"\n",
"# 2.2 Load Test Data\n",
"test_data_path = \"/home/mshahidul/readctrl/data/new_exp/test_health_literacy_data_manual_edit.json\"\n",
"with open(test_data_path, 'r') as f:\n",
" test_data = json.load(f)\n",
"\n",
"devset = []\n",
"for item in test_data:\n",
" unique_id = f\"{item['doc_id']}_{item['label']}\"\n",
" \n",
" if unique_id not in train_identifiers:\n",
" devset.append(dspy.Example(\n",
" source_text=item.get('fulltext', \"\"), \n",
" summary_text=item['gen_text'], \n",
" label=item['label']\n",
" ).with_inputs('source_text', 'summary_text'))\n",
"\n",
"print(f\"Dataset Stats: Train={len(trainset)}, Dev={len(devset)}\")\n",
"\n",
"# --- 3. Robust Signature & Module (Updated) ---\n",
"\n",
"class HealthLiteracySignature(dspy.Signature):\n",
" \"\"\"\n",
" Judge the health literacy level of a medical summary relative to its source text.\n",
" Analyze if the summary successfully simplifies technical medical concepts \n",
" for the intended literacy level.\n",
" \"\"\"\n",
" source_text: str = dspy.InputField(desc=\"The original technical medical document.\")\n",
" summary_text: str = dspy.InputField(desc=\"The generated summary to be analyzed.\")\n",
" \n",
" reasoning: str = dspy.OutputField(desc=\"Compare the summary to the source. Check for simplification of jargon and maintenance of core facts.\")\n",
" label: Literal[\"low_health_literacy\", \"intermediate_health_literacy\", \"proficient_health_literacy\"] = dspy.OutputField()\n",
"\n",
"class HealthLiteracyClassifier(dspy.Module):\n",
" def __init__(self):\n",
" super().__init__()\n",
" self.predictor = dspy.ChainOfThought(HealthLiteracySignature)\n",
"\n",
" def forward(self, source_text, summary_text):\n",
" return self.predictor(source_text=source_text, summary_text=summary_text)\n",
"\n",
"# --- 4. Metric and Optimization ---\n",
"\n",
"def health_literacy_metric(gold, pred, trace=None):\n",
" if not pred or not pred.label: return False\n",
" return gold.label.strip().lower() == pred.label.strip().lower()\n",
"\n",
"optimizer = BootstrapFewShotWithRandomSearch(\n",
" metric=health_literacy_metric,\n",
" max_bootstrapped_demos=3,\n",
" num_candidate_programs=8, \n",
" teacher_settings=dict(lm=openai_model_teacher)\n",
")\n",
"\n",
"optimized_program = optimizer.compile(HealthLiteracyClassifier(), trainset=trainset)\n",
"\n",
"# --- 5. Evaluation & Saving ---\n",
"\n",
"evaluator = Evaluate(devset=devset, metric=health_literacy_metric, num_threads=1, display_progress=True)\n",
"accuracy_score = evaluator(optimized_program)\n",
"\n",
"print(f\"\\nOptimization Complete. Final Accuracy: {accuracy_score}%\")\n",
"optimized_program.save(\"/home/mshahidul/readctrl/data/new_exp/optimized_health_classifier_gpt5-mini_v2_with_source.json\")"
]
},
{
"cell_type": "markdown",
"id": "68df2ee4",
"metadata": {},
"source": [
"### /home/mshahidul/readctrl/data/new_exp/few_shot_examples_manual_edit.json give good performance"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "96f1f99e",
"metadata": {},
"outputs": [],
"source": [
"print(f\"Final Accuracy on Test Set: {accuracy_score}%\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "f0e0fbb8",
"metadata": {},
"outputs": [],
"source": [
"# To load and use:\n",
"classifier = HealthLiteracyClassifier()\n",
"classifier.load(\"/home/mshahidul/readctrl/data/new_exp/optimized_health_classifier.json\")\n",
"path=\"/home/mshahidul/readctrl/data/new_exp/test_health_literacy_data.json\"\n",
"with open(path,'r') as f:\n",
" test_data = json.load(f)\n",
"for item in test_data:\n",
" expected_label = item['label']\n",
" text = item['gen_text']\n",
" result = classifier(summary_text=text)\n",
" if (result.label == expected_label):\n",
" print(f\"Correctly classified: {expected_label} ✅\")\n",
" else:\n",
" print(f\"Misclassified. Expected: {expected_label}, Got: {result.label} ❌\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "132453c8",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\n",
"\n",
"\n",
"\n",
"None\n"
]
}
],
"source": [
"import dspy\n",
"import json\n",
"from typing import Literal\n",
"from dspy.teleprompt import BootstrapFewShotWithRandomSearch\n",
"from dspy.evaluate import Evaluate\n",
"\n",
"# --- 1. LLM Configuration ---\n",
"# (Keeping your existing setup)\n",
"api_file = \"/home/mshahidul/api_new.json\"\n",
"with open(api_file, \"r\") as f:\n",
" api_keys = json.load(f)\n",
"openai_api_key = api_keys[\"openai\"]\n",
"\n",
"\n",
"openai_model_student = dspy.LM(model='gpt-5-mini', api_key=openai_api_key)\n",
"\n",
"dspy.configure(lm=openai_model_student)\n",
"class HealthLiteracySignature(dspy.Signature):\n",
" \"\"\"\n",
" Judge the health literacy level of a generated medical summary.\n",
" Identify if the language is suitable for a layperson (low) or requires medical expertise (proficient).\n",
" \"\"\"\n",
" summary_text: str = dspy.InputField(desc=\"The generated medical summary to be analyzed.\")\n",
" reasoning: str = dspy.OutputField(desc=\"Analysis of jargon, acronyms, and sentence complexity.\")\n",
" label: Literal[\"low_health_literacy\", \"intermediate_health_literacy\", \"proficient_health_literacy\"] = dspy.OutputField()\n",
"\n",
"class HealthLiteracyClassifier(dspy.Module):\n",
" def __init__(self):\n",
" super().__init__()\n",
" self.predictor = dspy.ChainOfThought(HealthLiteracySignature)\n",
"\n",
" def forward(self, summary_text):\n",
" return self.predictor(summary_text=summary_text)\n",
"\n",
"classifier = HealthLiteracyClassifier()\n",
"classifier.load(\"/home/mshahidul/readctrl/data/new_exp/optimized_health_classifier_gpt5-mini_v2.json\")\n",
"result = classifier(summary_text=text)\n"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "8700ac2b",
"metadata": {},
"outputs": [],
"source": [
"print(few_shot_data.keys())\n",
"print(few_shot_data['low_health_literacy'][0].keys())"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "9f8f1c6a",
"metadata": {},
"outputs": [],
"source": [
"def calculate_label_accuracy(data):\n",
" \"\"\"\n",
" Calculates the accuracy of health_literacy_label based on doc_rating.\n",
" \n",
" Mapping:\n",
" - 1-2: low_health_literacy\n",
" - 3: intermediate_health_literacy\n",
" - 4-5: proficient_health_literacy\n",
" \"\"\"\n",
" if not data:\n",
" return 0.0\n",
" \n",
" correct_matches = 0\n",
" total_docs = len(data)\n",
" \n",
" for entry in data:\n",
" rating = entry.get('doc_rating')\n",
" actual_label = entry.get('health_literacy_label')\n",
" \n",
" # Determine the expected label based on the rating\n",
" if rating in [1, 2]:\n",
" expected_label = \"low_health_literacy\"\n",
" elif rating == 3:\n",
" expected_label = \"intermediate_health_literacy\"\n",
" elif rating in [4, 5]:\n",
" expected_label = \"proficient_health_literacy\"\n",
" else:\n",
" expected_label = None # Handle unexpected ratings if necessary\n",
" \n",
" # Check if the actual label matches the expected label\n",
" if actual_label == expected_label:\n",
" correct_matches += 1\n",
" \n",
" accuracy = (correct_matches / total_docs) * 100\n",
" return accuracy\n",
"\n",
"import json\n",
"import os\n",
"all_path=\"/home/mshahidul/readctrl/data/annotators_validate_data\"\n",
"for path in os.listdir(all_path):\n",
" for file in os.listdir(os.path.join(all_path,path)):\n",
" if file.endswith(\".json\") and \"annotation_results\" in file:\n",
" full_path=os.path.join(all_path,path,file)\n",
" \n",
" with open(full_path,'r') as f:\n",
" dataset = json.load(f)\n",
"\n",
" accuracy_pct = calculate_label_accuracy(dataset)\n",
" if accuracy_pct > 50.0:\n",
" print(path)\n",
" print(f\"Accuracy: {accuracy_pct:.2f}%\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "3d0a3fb4",
"metadata": {},
"outputs": [],
"source": [
"import os\n",
"import json\n",
"import pandas as pd\n",
"from collections import Counter\n",
"\n",
"# Configuration\n",
"input_dir = '/home/mshahidul/readctrl/data/annotators_validate_data'\n",
"output_dir = '/home/mshahidul/readctrl/data/final_result'\n",
"output_file = os.path.join(output_dir, 'consolidated_ratings_threshold.json')\n",
"\n",
"# --- Helper for Label Mapping ---\n",
"def get_expected_label(rating):\n",
" if rating in [1, 2]:\n",
" return \"low_health_literacy\"\n",
" elif rating == 3:\n",
" return \"intermediate_health_literacy\"\n",
" elif rating in [4, 5]:\n",
" return \"proficient_health_literacy\"\n",
" return None\n",
"\n",
"# --- Accuracy Function ---\n",
"def calculate_label_accuracy(data):\n",
" if not data:\n",
" return 0.0\n",
" \n",
" correct_matches = 0\n",
" total_docs = len(data)\n",
" \n",
" for entry in data:\n",
" rating = entry.get('doc_rating')\n",
" actual_label = entry.get('health_literacy_label')\n",
" expected_label = get_expected_label(rating)\n",
" \n",
" if actual_label == expected_label:\n",
" correct_matches += 1\n",
" \n",
" return (correct_matches / total_docs) * 100\n",
"\n",
"# 1. Create the output directory\n",
"os.makedirs(output_dir, exist_ok=True)\n",
"\n",
"all_data = []\n",
"cnt=0\n",
"maxi=float('inf')\n",
"total=0\n",
"# 2. Collect data from folders\n",
"folders = [f for f in os.listdir(input_dir) if os.path.isdir(os.path.join(input_dir, f))]\n",
"\n",
"for folder in folders:\n",
" json_path = os.path.join(input_dir, folder, 'annotation_results.json')\n",
" \n",
" if os.path.exists(json_path):\n",
" with open(json_path, 'r') as f:\n",
" try:\n",
" entries = json.load(f)\n",
" accuracy_pct = calculate_label_accuracy(entries)\n",
" total+=1\n",
" if accuracy_pct > 55.0:\n",
" cnt+=1\n",
" maxi=min(maxi,len(entries))\n",
" for item in entries:\n",
" all_data.append({\n",
" 'doc_id': item.get('doc_id'),\n",
" 'health_literacy_label': item.get('health_literacy_label'),\n",
" 'rating': item.get('doc_rating')\n",
" })\n",
" else:\n",
" print(f\"Skipping folder '{folder}': Accuracy too low ({accuracy_pct:.2f}%)\")\n",
" except Exception as e:\n",
" print(f\"Skipping error in {json_path}: {e}\")\n",
"\n",
"# 3. Process data\n",
"if not all_data:\n",
" print(\"No data met the accuracy threshold.\")\n",
"else:\n",
" df = pd.DataFrame(all_data)\n",
" df = df.dropna(subset=['doc_id', 'health_literacy_label', 'rating'])\n",
"\n",
" # 4. Custom Aggregation Logic for Consensus\n",
" def get_constrained_mode(group):\n",
" \"\"\"\n",
" Calculates mode but prioritizes ratings that match the health_literacy_label.\n",
" \"\"\"\n",
" label = group['health_literacy_label'].iloc[0]\n",
" ratings = group['rating'].tolist()\n",
" counts = Counter(ratings)\n",
" \n",
" # Sort by frequency (descending)\n",
" most_common = counts.most_common()\n",
" \n",
" # Check if the most frequent rating matches the label category\n",
" for rating, count in most_common:\n",
" if get_expected_label(rating) == label:\n",
" return rating\n",
" \n",
" # Fallback: if no ratings match the label (unlikely given your 55% filter), \n",
" # just take the most frequent one.\n",
" return most_common[0][0]\n",
"\n",
" # Group and Aggregate\n",
" summary = df.groupby(['doc_id', 'health_literacy_label']).apply(\n",
" lambda x: pd.Series({\n",
" 'num_annotations': len(x),\n",
" 'mean_rating': x['rating'].mean(),\n",
" 'consensus_rating': get_constrained_mode(x),\n",
" 'rating_distribution': x['rating'].tolist()\n",
" })\n",
" ).reset_index()\n",
"\n",
" # 5. Save to JSON\n",
" summary.to_json(output_file, orient='records', indent=4)\n",
"\n",
" print(\"-\" * 30)\n",
" print(f\"Success! Processed {len(summary)} unique pairs.\")\n",
" print(f\"File saved at: {output_file}\")\n",
" print(summary.head())"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7ccf5e91",
"metadata": {},
"outputs": [],
"source": [
"# /home/mshahidul/readctrl/data/final_result/consolidated_ratings_threshold.json\n",
"with open(\"/home/mshahidul/readctrl/data/final_result/consolidated_ratings_threshold.json\", 'r') as f:\n",
" data = json.load(f)\n",
"doc={}\n",
"for item in data:\n",
" doc[(item['doc_id'],item['health_literacy_label'])]=item\n",
"for it in range(0,20):\n",
" for label in ['low_health_literacy','intermediate_health_literacy','proficient_health_literacy']:\n",
" if doc.get((it,label)) is None:\n",
" print(it,label)"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "0466c8f0",
"metadata": {},
"outputs": [],
"source": [
"# /home/mshahidul/readctrl/data/synthetic_dataset_diff_labels/syn_data_with_gs_summary_en.json\n",
"with open(\"/home/mshahidul/readctrl/data/synthetic_dataset_diff_labels/syn_data_with_gs_summary_en.json\", 'r') as f:\n",
" data = json.load(f)\n",
"print(f\"Label: low_health_literacy\")\n",
"id=2\n",
"print(f\"fulltext: {data[id]['fulltext']}\")\n",
"print(f\"gold summary: {data[id]['summary']}\")\n",
"print(f\"generated summary: {data[id]['diff_label_texts']['low_health_literacy']}\")"
]
},
{
"cell_type": "markdown",
"id": "13c234a2",
"metadata": {},
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "b89b4952",
"metadata": {},
"outputs": [],
"source": [
"import json\n",
"from collections import Counter\n",
"\n",
"# Load your data\n",
"file_path = '/home/mshahidul/readctrl/data/final_result/consolidated_ratings_threshold.json'\n",
"with open(file_path, 'r') as f:\n",
" data = json.load(f)\n",
"\n",
"def map_to_category(rating):\n",
" \"\"\"Maps 1-5 scale to Low, Med, High buckets.\"\"\"\n",
" if rating in [1, 2]:\n",
" return \"Low\"\n",
" elif rating == 3:\n",
" return \"Med\"\n",
" elif rating in [4, 5]:\n",
" return \"High\"\n",
" return None\n",
"\n",
"def get_agreement_type(ratings):\n",
" # Map 1-5 values to Low, Med, High\n",
" categories = [map_to_category(r) for r in ratings]\n",
" \n",
" counts = Counter(categories)\n",
" max_votes = max(counts.values())\n",
" num_annotators = len(categories)\n",
" \n",
" # Logic Update:\n",
" if max_votes == num_annotators:\n",
" return \"Unanimous\"\n",
" elif max_votes >= (num_annotators / 2):\n",
" # This captures 2 out of 3, or 2 out of 4, etc.\n",
" return \"Majority\"\n",
" else:\n",
" return \"Disputed\"\n",
"\n",
"# Counters\n",
"stats = {\"Unanimous\": 0, \"Majority\": 0, \"Disputed\": 0}\n",
"valid_count = 0\n",
"\n",
"for entry in data:\n",
" ratings = entry['rating_distribution']\n",
" \n",
" if len(ratings) < 2:\n",
" continue\n",
" \n",
" agreement = get_agreement_type(ratings)\n",
" stats[agreement] += 1\n",
" valid_count += 1\n",
"\n",
"print(f\"--- Final Agreement Distribution ---\")\n",
"print(f\"Total Documents: {valid_count}\\n\")\n",
"\n",
"for label, count in stats.items():\n",
" percentage = (count / valid_count) * 100 if valid_count > 0 else 0\n",
" print(f\"{label:10}: {count:4} notes ({percentage:6.2f}%)\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e28ee431",
"metadata": {},
"outputs": [],
"source": [
"total"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "43a3a839",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Length of the JSON file: 49\n",
"Keys of the first item: dict_keys(['id', 'fulltext', 'summary', 'translated_fulltext', 'translated_summary', 'judge_pass'])\n"
]
}
],
"source": [
"import json\n",
"\n",
"# Path to your JSON file\n",
"# Check length and attribute keys of the JSON file\n",
"\n",
"json_path = \"/home/mshahidul/readctrl/data/translated_data/translation_version_1/multiclinsum_gs_train_en2bn_gemma(0_200).json\"\n",
"with open(json_path, 'r') as f:\n",
" data = json.load(f)\n",
"\n",
"# Check length and attribute keys of the JSON file\n",
"print(f\"Length of the JSON file: {len(data)}\")\n",
"print(f\"Keys of the first item: {data[0].keys()}\")\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "542bc6cf",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"{'id': 'multiclinsum_gs_en_47.txt',\n",
" 'fulltext': 'We present here the case of a two-day old neonate with in-born right scrotal swelling admitted at Children’s hospital. The patient was born at term via cesarean section at a private hospital. He was kept in the nursery for one day. The examining doctor referred them for urgent surgical care, but it took them one day to arrive at our hospital. Upon arrival in the emergency department, he was well hydrated, pink at room temperature with good perfusion. Upon examination, the right testis was found to be enlarged, tense, non-tender visibly reddish with overlying skin excoriation. Trans-illumination was negative in the right but positive in the contralateral testis. Both hernial orifices were normal. All the laboratory investigations were performed with an urgent Doppler ultrasound of the inguinoscrotal area. The ultrasound examination found the right testis to be enlarged (15.6*9.4 mm) and showed heterogeneous hypoechoic texture with prominent rete testis and no flow on color Doppler analysis. Left testis appeared normal in size, shape and echotexture with minimal hydrocele. An urgent scrotal exploration was undertaken. Intra-operatively, there was frank necrotic right testis with intravaginal torsion of the testis with minimal hydrocele. A right orchidectomy and contralateral orchidopexy was then performed.',\n",
" 'summary': 'We present here the case of a two-day old neonate with in-born right scrotal swelling admitted at Children’s hospital. The patient was born at term via cesarean section at a private hospital. Upon arrival in the emergency department, he was well hydrated, pink at room temperature with good perfusion. Upon examination, the right testis was found to be enlarged, tense, non-tender visibly reddish with overlying skin excoriation. Trans-illumination was negative in right but positive in the contralateral testis. Both hernial orifices were normal. Doppler ultrasound of the inguinoscrotal area found the right testis to be enlarged (15.6*9.4 mm) and showed heterogeneous hypoechoic texture with prominent rete testis and no flow on color doppler analysis. An urgent scrotal exploration was undertaken. Intra-operatively there was frank necrotic right testis with intravaginal torsion of the testis and minimal hydrocele. A right orchidectomy and contralateral orchidopexy were performed.',\n",
" 'translated_fulltext': 'আমরা এখানে একটি দুই দিন বয়সী নবজাতকের ঘটনা তুলে ধরছি, যার জন্মগতভাবে ডান দিকের অণ্ডকোষে ফোলা ছিল এবং তাকে শিশু হাসপাতালে ভর্তি করা হয়েছে। শিশুটি একটি বেসরকারি হাসপাতালে সিজারিয়ান অপারেশনের মাধ্যমে নির্ধারিত সময়ে জন্মগ্রহণ করে। তাকে একদিনের জন্য নার্সারিতে রাখা হয়েছিল। যে ডাক্তার পরীক্ষা করেছিলেন, তিনি জরুরি ভিত্তিতে অস্ত্রোপচারের জন্য পরামর্শ দেন, কিন্তু তাদের হাসপাতালে আসতে এক দিন লেগে যায়। জরুরি বিভাগে আসার পর দেখা যায়, শিশুটি ভালোভাবে হাইড্রেটেড, স্বাভাবিক তাপমাত্রায় তার ত্বক গোলাপী এবং রক্ত সঞ্চালন স্বাভাবিক। পরীক্ষায় দেখা যায়, ডান দিকের অণ্ডকোষটি বড়, শক্ত, দৃশ্যত লালচে এবং এর উপরে ত্বকের সামান্য ক্ষয় হয়েছে। ডান দিকের অণ্ডকোষে ট্রান্স-ইলুমিনেশন নেগেটিভ ছিল, কিন্তু অন্য অণ্ডকোষে পজিটিভ। উভয় হার্নিয়াল ছিদ্র স্বাভাবিক ছিল। এরপর দ্রুততার সাথে ইনগুইনোস্ক্রোটাল অঞ্চলের ডপলার আলট্রাসাউন্ড করা হয় এবং অন্যান্য পরীক্ষাও করা হয়। আলট্রাসাউন্ড পরীক্ষায় দেখা যায়, ডান দিকের অণ্ডকোষটি বড় (15.6*9.4 মিমি) এবং এর মধ্যে বিভিন্ন ধরনের হাইপোইক টেক্সচার রয়েছে, রেটে টেস্টিস স্পষ্টভাবে দেখা যাচ্ছে এবং কালার ডপলার বিশ্লেষণে কোনো রক্ত প্রবাহ নেই। বাম দিকের অণ্ডকোষের আকার, আকৃতি এবং ইকোটেক্সচার স্বাভাবিক দেখা যায়, সামান্য হাইড্রোসেলও ছিল। এরপর জরুরি ভিত্তিতে স্ক্রোটাল এক্সপ্লোরেশন করা হয়। অস্ত্রোপচারের সময় দেখা যায়, ডান দিকের অণ্ডকোষে স্পষ্ট নেক্রোসিস হয়েছে এবং অণ্ডকোষের মধ্যে সামান্য হাইড্রোসেলসহ ইন্ট্রাভ্যাজাইনাল টর্শন রয়েছে। এরপর ডান দিকের অণ্ডকোষ অপসারণ (অর্কিডেক্টমি) এবং অন্য দিকের অণ্ডকোষকে সঠিক স্থানে স্থাপন (অর্কিডোপেক্সি) করা হয়।',\n",
" 'translated_summary': 'আমরা এখানে একটি দুই দিন বয়সী নবজাতকের ঘটনা তুলে ধরছি, যার জন্মগতভাবে ডান দিকের অণ্ডকোষে ফোলা ছিল এবং তাকে শিশু হাসপাতালে ভর্তি করা হয়েছে। শিশুটি একটি বেসরকারি হাসপাতালে সিজারিয়ান অপারেশনের মাধ্যমে নির্ধারিত সময়ে জন্মগ্রহণ করে। জরুরি বিভাগে আসার পর দেখা যায়, তার শরীর ভালোভাবে হাইড্রেটেড, স্বাভাবিক তাপমাত্রায় ত্বক গোলাপী এবং রক্ত সঞ্চালন স্বাভাবিক। পরীক্ষায় দেখা যায়, ডান দিকের অণ্ডকোষটি বড়, শক্ত, দৃশ্যত লালচে এবং এর উপরে ত্বকের সামান্য ক্ষয় হয়েছে। ডান দিকের অণ্ডকোষে আলো প্রবেশ করানো হলে তা দেখা যায়নি, কিন্তু বিপরীত দিকের অণ্ডকোষে আলো প্রবেশ করানো হলে তা দেখা গেছে। উভয় হার্নিয়াল ছিদ্র স্বাভাবিক ছিল। ইনগুইনোস্ক্রোটাল অঞ্চলের ডপলার আল্ট্রাসাউন্ডে দেখা যায়, ডান দিকের অণ্ডকোষটি বড় (১৫.৬*৯.৪ মিমি) এবং এর মধ্যে বিভিন্ন ধরনের হাইপোইক টেক্সচার রয়েছে, রেটে টেস্টিস স্পষ্টভাবে দেখা যাচ্ছে এবং কালার ডপলার বিশ্লেষণে কোনো রক্ত প্রবাহ দেখা যায়নি। দ্রুত স্ক্রোটাল এক্সপ্লোরেশন করা হয়। অপারেশনের সময় দেখা যায়, ডান দিকের অণ্ডকোষে স্পষ্ট নেক্রোসিস হয়েছে এবং অণ্ডকোষের ইন্ট্রাভ্যাজিনাল টরশন হয়েছে, সেই সাথে সামান্য হাইড্রোসেলও রয়েছে। এরপর ডান দিকের অণ্ডকোষ অপসারণ (অর্কিডেক্টমি) এবং বিপরীত দিকের অণ্ডকোষকে সঠিক স্থানে স্থাপন (অর্কিডোপেক্সি) করা হয়।',\n",
" 'judge_pass': True}"
]
},
"execution_count": 3,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"data[2]"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "un",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.11.14"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
|