U
    t75i                     @   st   d dl mZmZ d dlmZ d dlmZ d dlZd dlZd dl	Z	d dl
Z
e Zdd Zdd Zdd
dZdd ZdS )    )requestjsonify)chatgpt_call)PromptsNc                  C   s  zJdt jkr"tddddfW S t jd} t| dkrNtddddfW S g }| D ]}|jsdqV|j}d| kr\ztt	|}d	}|j
D ]}| }|r||d
 7 }q| r|d| |jd n|d t|}|| W nl tk
rX }	 zLtd|j dt|	  td|j dt|	 dddf W Y   W S d}	~	X Y nX qVd| krzt|}|| W nl tk
r }	 zLtd|j dt|	  td|j dt|	 dddf W Y   W S d}	~	X Y nX qVtd| ddddf  W S qV|s,tddddfW S t|}
t|
t| dddfW S  tk
r }	 z6tdt|	  tdt|	 dddf W Y S d}	~	X Y nX dS )z
    Accepts multiple files (PDF, images) and extracts medical data using AI
    Returns structured JSON - NO database storage (privacy-first)
    fileszNo files uploadedtrue)messageerrori  r   zNo files providedpdf 
Zpdf_texttypecontentfilenamezError processing PDF : i  NimagezError processing image zUnsupported file type: z$. Only PDF and images are supported.z2No data could be extracted from the uploaded filesF)dataZfiles_processedr	      z Error in parse_medical_reports: zError parsing reports: )r   r   r   getlistlenr   content_typelowerPyPDF2Z	PdfReaderZpagesZextract_textstripappendseekprocess_image_file	Exceptionprintstrparse_with_ai)r   extracted_datafileZ	file_typeZ
pdf_readertextpageZ	page_textZimage_resulteparsed_data r(   4/var/www/html/api-medvista/Services/report_parser.pyparse_medical_reports   s    





""
r*   c              
   C   s   z`t | }t }t j||dd |d | }t|	d}t
|| j}d|| jdW S  tk
r } ztdt| W 5 d}~X Y nX dS )	zj
    Process image file using imageio
    Reads image, converts to JPEG format, and encodes to base64
    ZJPEG)formatr   zutf-8r   r   z%Error processing image with imageio: N)imageioZimreadioBytesIOZimwriter   readbase64	b64encodedecodeparse_image_with_ai_visionr   r   r    )r#   r   Zimg_byte_arrZimage_bytesimage_base64Zextracted_textr&   r(   r(   r)   r   i   s    

r   r   c              
   C   s   ddl m} |ddd}zN|jjjdddd	d
dddddd|  idgd	gdd}|jd jjW S  tk
r } z6t	d| dt
|  d| dt
| d W Y S d}~X Y nX dS )za
    Use AI vision to extract text from medical images
    Works with DeepSeek vision models
    r   )OpenAIz#sk-e108ff73c53144379d0b8a4aefbaf525zhttps://api.deepseek.com)api_keybase_urlzdeepseek-chatsystemzYou are a medical document OCR expert. Extract ALL text and data from medical reports accurately, preserving the structure and format.)roler   userr$   aN  Extract all medical information from this report image. Include:
                            - Test names and their values
                            - Units and reference ranges
                            - Doctor's notes and observations
                            - Patient information (if visible)
                            - Any abnormal findings or flags
                            - Date of report
                            - Laboratory name
                            
                            Format the output as clear, structured text, preserving the original layout.)r   r$   	image_urlurlzdata:image/jpeg;base64,)r   r;   i  )modelmessages
max_tokenszVision API failed for r   z[Image data from z - vision processing failed: ]N)openair5   chatcompletionscreatechoicesr   r   r   r   r    )r4   r   r5   clientresponser&   r(   r(   r)   r3      s:     #r3   c                 C   s2   d}| dd | D }t|}t|dd}|S )z
    Send all extracted data to AI for structured parsing
    Combines text from all files and creates structured JSON output
    z

================================================================================
=== NEW DOCUMENT ===
================================================================================

c              	   S   s.   g | ]&}d |d  d|d  d|d  qS )u   📄 File: r   u   
📋 Type: r   u   

📝 Content:
r   r(   ).0itemr(   r(   r)   
<listcomp>   s   z!parse_with_ai.<locals>.<listcomp>i  )r?   )joinpromptsr*   r   )r"   	separatorZcombined_contentpromptr'   r(   r(   r)   r!      s    

r!   )r   )flaskr   r   Services.ai_workerr   Services.promptsr   r   r0   r,   r-   rL   r*   r   r3   r!   r(   r(   r(   r)   <module>   s   ]#
8