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
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
import logging
import re

import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer, pipeline


class MedicalReportAnalyzer:
    """

    A class for analyzing medical text reports using pre-trained NLP models from Hugging Face.



    This analyzer can:

    1. Extract medical entities (conditions, treatments, tests)

    2. Classify report severity

    3. Extract key findings

    4. Identify suggested follow-up actions

    """

    def __init__(

        self,

        ner_model="samrawal/bert-base-uncased_medical-ner",

        classifier_model="medicalai/ClinicalBERT",

        device=None,

    ):
        """

        Initialize the text analyzer with specific pre-trained models.



        Args:

            ner_model (str): Model for named entity recognition

            classifier_model (str): Model for text classification

            device (str, optional): Device to run models on ('cuda' or 'cpu')

        """
        self.logger = logging.getLogger(__name__)

        # Determine device
        if device is None:
            self.device = "cuda" if torch.cuda.is_available() else "cpu"
        else:
            self.device = device

        self.logger.info(f"Using device: {self.device}")

        # Load NER model for entity extraction
        try:
            self.ner_pipeline = pipeline(
                "token-classification",
                model=ner_model,
                aggregation_strategy="simple",
                device=0 if self.device == "cuda" else -1,
            )
            self.logger.info(f"Successfully loaded NER model: {ner_model}")
        except Exception as e:
            self.logger.error(f"Failed to load NER model: {e}")
            self.ner_pipeline = None

        # Load classifier model for severity assessment
        try:
            self.tokenizer = AutoTokenizer.from_pretrained(classifier_model)
            self.classifier = AutoModelForSequenceClassification.from_pretrained(
                classifier_model
            )
            self.classifier.to(self.device)
            self.classifier.eval()
            self.logger.info(
                f"Successfully loaded classifier model: {classifier_model}"
            )
        except Exception as e:
            self.logger.error(f"Failed to load classifier model: {e}")
            self.classifier = None

        # Severity levels mapping
        self.severity_levels = {
            0: "Normal",
            1: "Mild",
            2: "Moderate",
            3: "Severe",
            4: "Critical",
        }

        # Common medical findings and their severity levels
        self.finding_severity = {
            "pneumonia": 3,
            "fracture": 3,
            "tumor": 4,
            "nodule": 2,
            "mass": 3,
            "edema": 2,
            "effusion": 2,
            "hemorrhage": 3,
            "opacity": 1,
            "atelectasis": 2,
            "pneumothorax": 3,
            "consolidation": 2,
            "cardiomegaly": 2,
        }

    def extract_entities(self, text):
        """

        Extract medical entities from the report text.



        Args:

            text (str): Medical report text



        Returns:

            dict: Dictionary of entity lists by category

        """
        if not self.ner_pipeline:
            self.logger.warning("NER model not available")
            return {}

        try:
            # Run NER
            entities = self.ner_pipeline(text)

            # Group entities by type
            grouped_entities = {
                "problem": [],  # Medical conditions
                "test": [],  # Tests/procedures
                "treatment": [],  # Treatments/medications
                "anatomy": [],  # Anatomical locations
            }

            for entity in entities:
                entity_type = entity.get("entity_group", "").lower()

                # Map entity types to our categories
                if entity_type in ["problem", "disease", "condition", "diagnosis"]:
                    category = "problem"
                elif entity_type in ["test", "procedure", "examination"]:
                    category = "test"
                elif entity_type in ["treatment", "medication", "drug"]:
                    category = "treatment"
                elif entity_type in ["body_part", "anatomy", "organ"]:
                    category = "anatomy"
                else:
                    continue  # Skip other entity types

                word = entity.get("word", "")
                score = entity.get("score", 0)

                # Only include if confidence is reasonable
                if score > 0.7 and word not in grouped_entities[category]:
                    grouped_entities[category].append(word)

            return grouped_entities

        except Exception as e:
            self.logger.error(f"Error extracting entities: {e}")
            return {}

    def assess_severity(self, text):
        """

        Assess the severity level of the medical report.



        Args:

            text (str): Medical report text



        Returns:

            dict: Severity assessment including level and confidence

        """
        if not self.classifier:
            self.logger.warning("Classifier model not available")
            return {"level": "Unknown", "score": 0.0}

        try:
            # Use rule-based approach along with model
            severity_score = 0
            confidence = 0.5  # Start with neutral confidence

            # Check for severe keywords
            severe_keywords = [
                "severe",
                "critical",
                "urgent",
                "emergency",
                "immediate attention",
            ]
            moderate_keywords = ["moderate", "concerning", "follow-up", "monitor"]
            mild_keywords = ["mild", "minimal", "slight", "minor"]
            normal_keywords = [
                "normal",
                "unremarkable",
                "no abnormalities",
                "within normal limits",
            ]

            # Count keyword occurrences
            text_lower = text.lower()
            severe_count = sum(text_lower.count(word) for word in severe_keywords)
            moderate_count = sum(text_lower.count(word) for word in moderate_keywords)
            mild_count = sum(text_lower.count(word) for word in mild_keywords)
            normal_count = sum(text_lower.count(word) for word in normal_keywords)

            # Adjust severity based on keyword counts
            if severe_count > 0:
                severity_score += min(severe_count, 2) * 1.5
                confidence += 0.1
            if moderate_count > 0:
                severity_score += min(moderate_count, 3) * 0.75
                confidence += 0.05
            if mild_count > 0:
                severity_score += min(mild_count, 3) * 0.25
                confidence += 0.05
            if normal_count > 0:
                severity_score -= min(normal_count, 3) * 0.75
                confidence += 0.1

            # Check for specific medical findings
            for finding, level in self.finding_severity.items():
                if finding in text_lower:
                    severity_score += level * 0.5
                    confidence += 0.05

            # Normalize severity score to 0-4 range
            severity_score = max(0, min(4, severity_score))
            severity_level = int(round(severity_score))

            # Map to severity level
            severity = self.severity_levels.get(severity_level, "Moderate")

            # Cap confidence at 0.95
            confidence = min(0.95, confidence)

            return {
                "level": severity,
                "score": round(severity_score, 1),
                "confidence": round(confidence, 2),
            }

        except Exception as e:
            self.logger.error(f"Error assessing severity: {e}")
            return {"level": "Unknown", "score": 0.0, "confidence": 0.0}

    def extract_findings(self, text):
        """

        Extract key clinical findings from the report.



        Args:

            text (str): Medical report text



        Returns:

            list: List of key findings

        """
        try:
            # Split text into sentences
            sentences = re.split(r"[.!?]\s+", text)
            findings = []

            # Key phrases that often introduce findings
            finding_markers = [
                "finding",
                "observed",
                "noted",
                "shows",
                "reveals",
                "demonstrates",
                "indicates",
                "evident",
                "apparent",
                "consistent with",
                "suggestive of",
            ]

            # Negative markers
            negation_markers = ["no", "not", "none", "negative", "without", "denies"]

            for sentence in sentences:
                # Skip very short sentences
                if len(sentence.split()) < 3:
                    continue

                sentence = sentence.strip()

                # Check if this sentence likely contains a finding
                contains_finding_marker = any(
                    marker in sentence.lower() for marker in finding_markers
                )

                # Check for negation
                contains_negation = any(
                    marker in sentence.lower().split() for marker in negation_markers
                )

                # Only include positive findings or explicitly negated findings that are important
                if contains_finding_marker or (
                    contains_negation
                    and any(
                        term in sentence.lower()
                        for term in self.finding_severity.keys()
                    )
                ):
                    findings.append(sentence)

            return findings

        except Exception as e:
            self.logger.error(f"Error extracting findings: {e}")
            return []

    def suggest_followup(self, text, entities, severity):
        """

        Suggest follow-up actions based on report analysis.



        Args:

            text (str): Medical report text

            entities (dict): Extracted entities

            severity (dict): Severity assessment



        Returns:

            list: Suggested follow-up actions

        """
        try:
            followups = []

            # Base recommendations on severity
            severity_level = severity.get("level", "Unknown")
            severity_score = severity.get("score", 0)

            # Extract problems from entities
            problems = entities.get("problem", [])

            # Check if follow-up is already mentioned in the text
            followup_mentioned = any(
                phrase in text.lower()
                for phrase in [
                    "follow up",
                    "follow-up",
                    "followup",
                    "return",
                    "refer",
                    "consult",
                ]
            )

            # Default recommendations based on severity
            if severity_level == "Critical":
                followups.append("Immediate specialist consultation recommended.")

            elif severity_level == "Severe":
                followups.append("Prompt follow-up with specialist is recommended.")

                # Add specific recommendations for common severe conditions
                for problem in problems:
                    if "pneumonia" in problem.lower():
                        followups.append(
                            "Consider antibiotic therapy and close monitoring."
                        )
                    elif "fracture" in problem.lower():
                        followups.append(
                            "Orthopedic consultation for treatment planning."
                        )
                    elif "mass" in problem.lower() or "tumor" in problem.lower():
                        followups.append(
                            "Further imaging and possible biopsy recommended."
                        )

            elif severity_level == "Moderate":
                followups.append("Follow-up with primary care physician recommended.")
                if not followup_mentioned and problems:
                    followups.append(
                        "Consider additional imaging or tests for further evaluation."
                    )

            elif severity_level == "Mild":
                if problems:
                    followups.append(
                        "Routine follow-up with primary care physician as needed."
                    )
                else:
                    followups.append("No immediate follow-up required.")

            else:  # Normal
                followups.append(
                    "No specific follow-up indicated based on this report."
                )

            # Check for specific findings that always need follow-up
            for critical_term in ["mass", "tumor", "nodule", "opacity"]:
                if (
                    critical_term in text.lower()
                    and "follow-up" not in " ".join(followups).lower()
                ):
                    followups.append(
                        f"Follow-up imaging recommended to monitor {critical_term}."
                    )
                    break

            return followups

        except Exception as e:
            self.logger.error(f"Error suggesting follow-up: {e}")
            return ["Unable to generate follow-up recommendations."]

    def analyze(self, text):
        """

        Perform comprehensive analysis of medical report text.



        Args:

            text (str): Medical report text



        Returns:

            dict: Complete analysis results

        """
        try:
            # Extract entities
            entities = self.extract_entities(text)

            # Assess severity
            severity = self.assess_severity(text)

            # Extract key findings
            findings = self.extract_findings(text)

            # Generate follow-up suggestions
            followups = self.suggest_followup(text, entities, severity)

            # Create detailed report
            report = {
                "entities": entities,
                "severity": severity,
                "findings": findings,
                "followup_recommendations": followups,
            }

            return report

        except Exception as e:
            self.logger.error(f"Error analyzing report: {e}")
            return {"error": str(e)}


# Example usage
if __name__ == "__main__":
    # Set up logging
    logging.basicConfig(level=logging.INFO)

    # Test on a sample report
    analyzer = MedicalReportAnalyzer()

    sample_report = """

    CHEST X-RAY EXAMINATION

    

    CLINICAL HISTORY: 55-year-old male with cough and fever.

    

    FINDINGS: The heart size is at the upper limits of normal. The lungs are clear without focal consolidation, 

    effusion, or pneumothorax. There is mild prominence of the pulmonary vasculature. No pleural effusion is seen. 

    There is a small nodular opacity noted in the right lower lobe measuring approximately 8mm, which is suspicious 

    and warrants further investigation. The mediastinum is unremarkable. The visualized bony structures show no acute abnormalities.

    

    IMPRESSION:

    1. Mild cardiomegaly.

    2. 8mm nodular opacity in the right lower lobe, recommend follow-up CT for further evaluation.

    3. No acute pulmonary parenchymal abnormality.

    

    RECOMMENDATIONS: Follow-up chest CT to further characterize the nodular opacity in the right lower lobe.

    """

    results = analyzer.analyze(sample_report)

    print("\nMedical Report Analysis:")
    print(
        f"\nSeverity: {results['severity']['level']} (Score: {results['severity']['score']})"
    )

    print("\nKey Findings:")
    for finding in results["findings"]:
        print(f"- {finding}")

    print("\nEntities:")
    for category, items in results["entities"].items():
        if items:
            print(f"- {category.capitalize()}: {', '.join(items)}")

    print("\nFollow-up Recommendations:")
    for rec in results["followup_recommendations"]:
        print(f"- {rec}")