Spaces:
Build error
Build error
Upload 4 files
Browse files
text_classifier/__init__.py
ADDED
|
File without changes
|
text_classifier/__pycache__/__init__.cpython-312.pyc
ADDED
|
Binary file (179 Bytes). View file
|
|
|
text_classifier/__pycache__/classifier.cpython-312.pyc
ADDED
|
Binary file (3.51 kB). View file
|
|
|
text_classifier/classifier.py
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# # classifier.py
|
| 2 |
+
|
| 3 |
+
# import os
|
| 4 |
+
# import json
|
| 5 |
+
# import re
|
| 6 |
+
# import logging
|
| 7 |
+
# import together
|
| 8 |
+
# from together import Together
|
| 9 |
+
|
| 10 |
+
# # Setup logging
|
| 11 |
+
# logging.basicConfig(level=logging.INFO)
|
| 12 |
+
|
| 13 |
+
# # Load API key
|
| 14 |
+
# api_key = os.environ.get("TOGETHER_API_KEY")
|
| 15 |
+
# if not api_key:
|
| 16 |
+
# raise ValueError("TOGETHER_API_KEY environment variable not set!")
|
| 17 |
+
|
| 18 |
+
# model_name = "meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo"
|
| 19 |
+
# client = Together(api_key=api_key)
|
| 20 |
+
|
| 21 |
+
# def extract_medical_info(text):
|
| 22 |
+
# prompt = f"""
|
| 23 |
+
# You are a medical information extractor. From the following text, extract:
|
| 24 |
+
|
| 25 |
+
# Doctor Name: (e.g. Dr. R. Keshwani)
|
| 26 |
+
# Patient Name:
|
| 27 |
+
# Medications[dosage]:
|
| 28 |
+
# med1: dosage1
|
| 29 |
+
# med2: dosage2
|
| 30 |
+
# med3: dosage3
|
| 31 |
+
|
| 32 |
+
# Only return the fields in the above format. Do not add extra information.
|
| 33 |
+
|
| 34 |
+
# Text:
|
| 35 |
+
# {text}
|
| 36 |
+
# """
|
| 37 |
+
|
| 38 |
+
# try:
|
| 39 |
+
# stream = client.chat.completions.create(
|
| 40 |
+
# model=model_name,
|
| 41 |
+
# messages=[{"role": "user", "content": prompt}],
|
| 42 |
+
# stream=True,
|
| 43 |
+
# )
|
| 44 |
+
|
| 45 |
+
# output = ""
|
| 46 |
+
# for chunk in stream:
|
| 47 |
+
# if hasattr(chunk, "choices") and chunk.choices:
|
| 48 |
+
# delta = chunk.choices[0].delta
|
| 49 |
+
# if hasattr(delta, "content") and delta.content:
|
| 50 |
+
# output += delta.content
|
| 51 |
+
|
| 52 |
+
# logging.info(f"Model Output:\n{output}")
|
| 53 |
+
|
| 54 |
+
# # Extract fields
|
| 55 |
+
# doctor_match = re.search(r'Doctor Name:\s*(.*)', output)
|
| 56 |
+
# patient_match = re.search(r'Patient Name:\s*(.*)', output)
|
| 57 |
+
# meds_block = re.search(r'Medications\[dosage\]\s*:?[\n\r]+((?:.+[\n\r]*)+)', output)
|
| 58 |
+
|
| 59 |
+
# doctor_name = doctor_match.group(1).strip() if doctor_match else ""
|
| 60 |
+
# patient_name = patient_match.group(1).strip() if patient_match else ""
|
| 61 |
+
# medications = []
|
| 62 |
+
|
| 63 |
+
# if meds_block:
|
| 64 |
+
# for line in meds_block.group(1).splitlines():
|
| 65 |
+
# if line.strip():
|
| 66 |
+
# med_match = re.match(r'(.+?)[:\-]\s*(.+)', line.strip())
|
| 67 |
+
# if med_match:
|
| 68 |
+
# medications.append(f"{med_match.group(1).strip()}: {med_match.group(2).strip()}")
|
| 69 |
+
# else:
|
| 70 |
+
# medications.append(line.strip())
|
| 71 |
+
|
| 72 |
+
# return {
|
| 73 |
+
# "doctor_name": doctor_name,
|
| 74 |
+
# "patient_name": patient_name,
|
| 75 |
+
# "medications": medications
|
| 76 |
+
# }
|
| 77 |
+
|
| 78 |
+
# except Exception as e:
|
| 79 |
+
# logging.error(f"Extraction failed: {e}")
|
| 80 |
+
# return {"error": f"An unexpected error occurred: {e}"}
|
| 81 |
+
|
| 82 |
+
# def extract_and_save_medical_info(text, output_dir="output"):
|
| 83 |
+
# info = extract_medical_info(text)
|
| 84 |
+
# if "error" in info:
|
| 85 |
+
# return None, info["error"]
|
| 86 |
+
|
| 87 |
+
# os.makedirs(output_dir, exist_ok=True)
|
| 88 |
+
# output_path = os.path.join(output_dir, "extracted_info.json")
|
| 89 |
+
# with open(output_path, "w", encoding="utf-8") as f:
|
| 90 |
+
# json.dump(info, f, indent=4)
|
| 91 |
+
|
| 92 |
+
# return output_path, None
|
| 93 |
+
|
| 94 |
+
import os
|
| 95 |
+
import json
|
| 96 |
+
import together
|
| 97 |
+
from together import Together
|
| 98 |
+
|
| 99 |
+
# Load the API key from environment variables
|
| 100 |
+
api_key = os.environ.get("TOGETHER_API_KEY")
|
| 101 |
+
if not api_key:
|
| 102 |
+
raise ValueError("TOGETHER_API_KEY environment variable not set!")
|
| 103 |
+
|
| 104 |
+
# Define the model
|
| 105 |
+
model_name = "meta-llama/Llama-3.2-11B-Vision-Instruct-Turbo"
|
| 106 |
+
|
| 107 |
+
# Initialize the Together client
|
| 108 |
+
client = Together(api_key=api_key)
|
| 109 |
+
|
| 110 |
+
def extract_medical_info(text):
|
| 111 |
+
"""
|
| 112 |
+
Extracts doctor name, patient name, and medication names (without dosage) from the medical text.
|
| 113 |
+
Returns a dictionary with 'doctor_name', 'patient_name', and 'medications' fields.
|
| 114 |
+
"""
|
| 115 |
+
|
| 116 |
+
prompt = f"""
|
| 117 |
+
You are a medical assistant. Read the following medical text and extract structured data.
|
| 118 |
+
|
| 119 |
+
Return the output in strict JSON format with only these fields:
|
| 120 |
+
- doctor_name (string)
|
| 121 |
+
- patient_name (string)
|
| 122 |
+
- medications (list of medicine names only — no dosages)
|
| 123 |
+
|
| 124 |
+
Example:
|
| 125 |
+
{{
|
| 126 |
+
"doctor_name": "Dr. A. Kumar",
|
| 127 |
+
"patient_name": "S. Lalanga",
|
| 128 |
+
"medications": ["OFLATEST", "AZENAC - MR", "ANDIAL", "ZOFER"]
|
| 129 |
+
}}
|
| 130 |
+
|
| 131 |
+
Text:
|
| 132 |
+
\"\"\"{text}\"\"\"
|
| 133 |
+
"""
|
| 134 |
+
|
| 135 |
+
try:
|
| 136 |
+
# Use non-streaming mode for easier parsing
|
| 137 |
+
response = client.chat.completions.create(
|
| 138 |
+
model=model_name,
|
| 139 |
+
messages=[{"role": "user", "content": prompt}],
|
| 140 |
+
stream=False
|
| 141 |
+
)
|
| 142 |
+
raw_output = response.choices[0].message.content.strip()
|
| 143 |
+
print(f"DEBUG: Raw output from API:\n{raw_output}")
|
| 144 |
+
|
| 145 |
+
# Try parsing raw output directly
|
| 146 |
+
try:
|
| 147 |
+
result = json.loads(raw_output)
|
| 148 |
+
except json.JSONDecodeError:
|
| 149 |
+
# Attempt to extract valid JSON from within the output
|
| 150 |
+
import re
|
| 151 |
+
match = re.search(r'{.*}', raw_output, re.DOTALL)
|
| 152 |
+
if match:
|
| 153 |
+
result = json.loads(match.group(0))
|
| 154 |
+
else:
|
| 155 |
+
raise ValueError("Could not extract valid JSON from model output.")
|
| 156 |
+
|
| 157 |
+
return result
|
| 158 |
+
|
| 159 |
+
except Exception as e:
|
| 160 |
+
return {"error": f"An error occurred: {e}"}
|
| 161 |
+
|
| 162 |
+
def extract_and_save_medical_info(text, output_dir="output"):
|
| 163 |
+
"""
|
| 164 |
+
Extract info and save it to a JSON file in output_dir.
|
| 165 |
+
"""
|
| 166 |
+
print("DEBUG: Extracting medical info...")
|
| 167 |
+
info = extract_medical_info(text)
|
| 168 |
+
if "error" in info:
|
| 169 |
+
return None, info["error"]
|
| 170 |
+
|
| 171 |
+
os.makedirs(output_dir, exist_ok=True)
|
| 172 |
+
output_path = os.path.join(output_dir, "extracted_info.json")
|
| 173 |
+
with open(output_path, "w", encoding="utf-8") as f:
|
| 174 |
+
json.dump(info, f, indent=4)
|
| 175 |
+
|
| 176 |
+
return output_path, None
|
| 177 |
+
|
| 178 |
+
# # Example usage
|
| 179 |
+
# text = """
|
| 180 |
+
# Analyzing ./data/2.jpg...
|
| 181 |
+
# Dr. R. Keshwani M.B.B.S., PGDHS (Diabetology) General Physician and Diabetologist
|
| 182 |
+
# Consultant Diabetologist: Sunshine Hospital, Pace Hospital, Dr. Agarwal's Eye Hospital, Secunderabad Womens Hospital.
|
| 183 |
+
# Ex. Resident: Care Hospital
|
| 184 |
+
# Mobile No.: 98490 36918
|
| 185 |
+
# Email: drkeshwani@gmail.com
|
| 186 |
+
|
| 187 |
+
# 1. Tabs metrozil 02 - 6 1 - 1
|
| 188 |
+
# 2. Tabs amoxinine - MR - 6 1 - 1
|
| 189 |
+
# 3. Tabs rantac 1 1 2
|
| 190 |
+
# 4. Tabs ZOFER 1 *3days*
|
| 191 |
+
# S. Lalanga.
|
| 192 |
+
# """
|
| 193 |
+
|
| 194 |
+
# output_path, err = extract_and_save_medical_info(text)
|
| 195 |
+
# print(f"Saved to: {output_path}, Error: {err}")
|
| 196 |
+
# print("Extracted:", extract_medical_info(text))
|