# # 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))