a
    _h                     @   s  d dl Z d dlZd dlZd dlZd dlmZmZmZmZ d dl	m
Z
 d dlmZ d dlmZmZmZ d dlmZ d dlmZ d dlmZ d d	lmZ d d
lmZ ddlmZmZ dd Zeeeeeef f dddZ dd Z!eeeeee f dddZ"eedddZ#dS )    N)ListTupleDictAny)Image)BytesIO)VectorStoreIndexSimpleDirectoryReaderDocument)SimpleNodeParser)
OpenRouter)OpenAIEmbedding)Settings)settings   )MedicalRecordChatSessionc                  C   s:   t tdddd} ttddd}| t_|t_| |fS )NOPENROUTER_API_KEYzdeepseek/deepseek-chatgffffff?)api_keymodelZtemperatureZOPENAI_API_KEYztext-embedding-3-small)r   r   )r   osgetenvr   r   llmZembed_model)r   Z	embedding r   0/home/qiu/health_record_app/backend/api/utils.pyinit_llm   s    r   )
image_pathreturnc              
   C   sT  zt | d(}| }t|d}W d    n1 s<0    Y  t | }|j|j|j|j	d}dt
d dd}dd	d
ddddd| idgdgd}tjd||d}|jdkr| }	|	d d d d }
d|d< d|d< |
|fW S d|d< |j|d< d|fW S W n8 tyN } zddt|d fW  Y d }~S d }~0 0 d S )!Nrbzutf-8)widthheightformatmodezBearer r   zapplication/json)AuthorizationzContent-Typezgoogle/gemini-flash-1.5-8busertextzExtract all text from this medical document image. Include all details like patient information, dates, test results, medications, diagnoses, and any other relevant medical information. Format the output clearly.)typer%   	image_urlurlzdata:image/jpeg;base64,)r&   r'   rolecontent)r   messagesz-https://openrouter.ai/api/v1/chat/completions)headersjson   choicesr   messager+   Zextraction_modelsuccessextraction_statusfailederror )r3   r5   )openreadbase64	b64encodedecoder   r   r    r!   r"   r   r   requestspoststatus_coder.   r%   	Exceptionstr)r   Zimg_fileZ
image_dataZbase64_imageimgmetadatar-   dataresponseresultextracted_texter   r   r   extract_text_from_image%   sZ    .
	



rH   c                 C   s   g }t jj| d}|D ]}d|j d}|d|  d7 }|d|jd d7 }|jrl|d|j d7 }|jr|d|j d7 }t	||j
|j|j|j d	d
}|| q|sd S t  t|}|S )N)r$   zTitle: 
zType: zDate: z%Y-%m-%dzDescription: z
Extracted Content:
)	record_idrecord_type	file_type
created_at)r%   rB   )r   objectsfiltertitleget_record_type_displayrM   strftimedescriptionrF   r
   idrK   rL   	isoformatappendr   r   Zfrom_documents)r$   	documentsrecordsrecordr+   docindexr   r   r   create_user_indexi   s0    	
r\   )r1   sessionr   c              
   C   s  zt |}|sdg fW S |jdd d }ddd t|D }d| d|  d	}| }||}g }	t|d
r|jD ]J}
d|
j	v r||
j	d }zt
jj|d}|	| W q| t
jy   Y q|0 q|t||	fW S  ty } zdt| g fW  Y d }~S d }~0 0 d S )Nz[I don't have access to any of your medical records yet. Please upload some documents first.z-created_at   rI   c                 S   s   g | ]}|j  d |j qS )z: r)   ).0msgr   r   r   
<listcomp>   s   z(process_chat_message.<locals>.<listcomp>zMBased on the user's medical records and the following conversation history:

z

User's new question: z

Please provide a helpful response based on the medical records available. If you reference specific records, mention them clearly.source_nodesrJ   )rT   z0I encountered an error processing your request: )r\   r,   order_byjoinreversedZas_query_enginequeryhasattrrb   rB   r   rN   getrV   DoesNotExistr@   r?   )r1   r]   r$   r[   Zrecent_messagesZchat_historyrf   Zquery_enginerD   referenced_recordsnoderJ   rY   rG   r   r   r   process_chat_message   s8    

	




rl   )pdf_pathr   c                 C   s   dS )Nz'PDF text extraction not yet implementedr   )rm   r   r   r   extract_text_from_pdf   s    rn   )$r   r.   r9   r<   typingr   r   r   r   PILr   ior   Zllama_index.corer   r	   r
   Zllama_index.core.node_parserr   Zllama_index.llms.openrouterr   Zllama_index.embeddings.openair   r   django.confr   django_settingsmodelsr   r   r   r@   rH   r\   rl   rn   r   r   r   r   <module>   s*    D'3