{ "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 }