File size: 6,298 Bytes
667ad21
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# # classifier.py

# import os
# import json
# import re
# import logging
# import together
# from together import Together

# # Setup logging
# logging.basicConfig(level=logging.INFO)

# # Load API key
# api_key = os.environ.get("TOGETHER_API_KEY")
# if not api_key:
#     raise ValueError("TOGETHER_API_KEY environment variable not set!")

# model_name = "meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo"
# client = Together(api_key=api_key)

# def extract_medical_info(text):
#     prompt = f"""
# You are a medical information extractor. From the following text, extract:

# Doctor Name: (e.g. Dr. R. Keshwani)
# Patient Name: 
# Medications[dosage]:
# med1: dosage1
# med2: dosage2
# med3: dosage3

# Only return the fields in the above format. Do not add extra information.

# Text:
# {text}
# """

#     try:
#         stream = client.chat.completions.create(
#             model=model_name,
#             messages=[{"role": "user", "content": prompt}],
#             stream=True,
#         )

#         output = ""
#         for chunk in stream:
#             if hasattr(chunk, "choices") and chunk.choices:
#                 delta = chunk.choices[0].delta
#                 if hasattr(delta, "content") and delta.content:
#                     output += delta.content

#         logging.info(f"Model Output:\n{output}")

#         # Extract fields
#         doctor_match = re.search(r'Doctor Name:\s*(.*)', output)
#         patient_match = re.search(r'Patient Name:\s*(.*)', output)
#         meds_block = re.search(r'Medications\[dosage\]\s*:?[\n\r]+((?:.+[\n\r]*)+)', output)

#         doctor_name = doctor_match.group(1).strip() if doctor_match else ""
#         patient_name = patient_match.group(1).strip() if patient_match else ""
#         medications = []

#         if meds_block:
#             for line in meds_block.group(1).splitlines():
#                 if line.strip():
#                     med_match = re.match(r'(.+?)[:\-]\s*(.+)', line.strip())
#                     if med_match:
#                         medications.append(f"{med_match.group(1).strip()}: {med_match.group(2).strip()}")
#                     else:
#                         medications.append(line.strip())

#         return {
#             "doctor_name": doctor_name,
#             "patient_name": patient_name,
#             "medications": medications
#         }

#     except Exception as e:
#         logging.error(f"Extraction failed: {e}")
#         return {"error": f"An unexpected error occurred: {e}"}

# def extract_and_save_medical_info(text, output_dir="output"):
#     info = extract_medical_info(text)
#     if "error" in info:
#         return None, info["error"]

#     os.makedirs(output_dir, exist_ok=True)
#     output_path = os.path.join(output_dir, "extracted_info.json")
#     with open(output_path, "w", encoding="utf-8") as f:
#         json.dump(info, f, indent=4)

#     return output_path, None

import os
import json
import together
from together import Together

# Load the API key from environment variables
api_key = os.environ.get("TOGETHER_API_KEY")
if not api_key:
    raise ValueError("TOGETHER_API_KEY environment variable not set!")

# Define the model
model_name = "meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo"

# Initialize the Together client
client = Together(api_key=api_key)

def extract_medical_info(text):
    """

    Extracts doctor name, patient name, and medication names (without dosage) from the medical text.

    Returns a dictionary with 'doctor_name', 'patient_name', and 'medications' fields.

    """

    prompt = f"""

You are a medical assistant. Read the following medical text and extract structured data.



Return the output in strict JSON format with only these fields:

- doctor_name (string)

- patient_name (string)

- medications (list of medicine names only — no dosages)



Example:

{{

  "doctor_name": "Dr. A. Kumar",

  "patient_name": "S. Lalanga",

  "medications": ["OFLATEST", "AZENAC - MR", "ANDIAL", "ZOFER"]

}}



Text:

\"\"\"{text}\"\"\"

"""

    try:
        # Use non-streaming mode for easier parsing
        response = client.chat.completions.create(
            model=model_name,
            messages=[{"role": "user", "content": prompt}],
            stream=False
        )
        raw_output = response.choices[0].message.content.strip()
        print(f"DEBUG: Raw output from API:\n{raw_output}")

        # Try parsing raw output directly
        try:
            result = json.loads(raw_output)
        except json.JSONDecodeError:
            # Attempt to extract valid JSON from within the output
            import re
            match = re.search(r'{.*}', raw_output, re.DOTALL)
            if match:
                result = json.loads(match.group(0))
            else:
                raise ValueError("Could not extract valid JSON from model output.")

        return result

    except Exception as e:
        return {"error": f"An error occurred: {e}"}

def extract_and_save_medical_info(text, output_dir="output"):
    """

    Extract info and save it to a JSON file in output_dir.

    """
    print("DEBUG: Extracting medical info...")
    info = extract_medical_info(text)
    if "error" in info:
        return None, info["error"]

    os.makedirs(output_dir, exist_ok=True)
    output_path = os.path.join(output_dir, "extracted_info.json")
    with open(output_path, "w", encoding="utf-8") as f:
        json.dump(info, f, indent=4)

    return output_path, None

# # Example usage
# text = """
# Analyzing ./data/2.jpg...
# Dr. R. Keshwani M.B.B.S., PGDHS (Diabetology) General Physician and Diabetologist
# Consultant Diabetologist: Sunshine Hospital, Pace Hospital, Dr. Agarwal's Eye Hospital, Secunderabad Womens Hospital.
# Ex. Resident: Care Hospital
# Mobile No.: 98490 36918
# Email: drkeshwani@gmail.com

# 1. Tabs metrozil 02 - 6 1 - 1
# 2. Tabs amoxinine - MR - 6 1 - 1
# 3. Tabs rantac 1 1 2
# 4. Tabs ZOFER 1 *3days*
# S. Lalanga.
# """

# output_path, err = extract_and_save_medical_info(text)
# print(f"Saved to: {output_path}, Error: {err}")
# print("Extracted:", extract_medical_info(text))