rijdev commited on
Commit
2a07d13
·
verified ·
1 Parent(s): 9155e52

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +51 -0
app.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import TrOCRProcessor, VisionEncoderDecoderModel
2
+ from PIL import Image
3
+ import os
4
+ import re
5
+
6
+ # Load Hugging Face OCR model
7
+ processor = TrOCRProcessor.from_pretrained("microsoft/trocr-base-stage1")
8
+ model = VisionEncoderDecoderModel.from_pretrained("microsoft/trocr-base-stage1")
9
+
10
+ # Directory where patient records are stored
11
+ PATIENT_RECORDS_DIR = "records/"
12
+
13
+ # Function to extract patient name from filename
14
+ def extract_patient_name(file_name):
15
+ match = re.match(r"([A-Za-z]+[A-Za-z]*)_.*\.(jpg|png|jpeg|pdf)$", file_name)
16
+ if match:
17
+ return match.group(1)
18
+ return None
19
+
20
+ # OCR function
21
+ def extract_text_from_image(image_path):
22
+ image = Image.open(image_path).convert("RGB")
23
+ pixel_values = processor(images=image, return_tensors="pt").pixel_values
24
+ generated_ids = model.generate(pixel_values)
25
+ generated_text = processor.batch_decode(generated_ids, skip_special_tokens=True)[0]
26
+ return generated_text.strip()
27
+
28
+ # Save text to patient record
29
+ def save_to_patient_record(patient_name, text):
30
+ os.makedirs(PATIENT_RECORDS_DIR, exist_ok=True)
31
+ filepath = os.path.join(PATIENT_RECORDS_DIR, f"{patient_name}_records.txt")
32
+ with open(filepath, "a") as file:
33
+ file.write("\n\n===== New Upload =====\n")
34
+ file.write(text)
35
+
36
+ # Main process
37
+ def process_uploaded_lab_result(file_path):
38
+ print(f"Processing: {file_path}")
39
+ patient_name = extract_patient_name(os.path.basename(file_path))
40
+ if not patient_name:
41
+ return "❌ Could not determine patient name from filename."
42
+
43
+ ocr_text = extract_text_from_image(file_path)
44
+ save_to_patient_record(patient_name, ocr_text)
45
+ return f"✅ OCR completed and saved under {patient_name}'s record."
46
+
47
+ # Example usage
48
+ if __name__ == "__main__":
49
+ file_to_upload = "JuanDelaCruz_2025-06-13.jpg" # Example uploaded file
50
+ result = process_uploaded_lab_result(file_to_upload)
51
+ print(result)