
    qhR                        d dl Z d dlZd dlZd dlZd dlZd dlZd dlZd dlZd dlZd dl	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lmZmZmZmZmZmZ d d	lmZ d dlZd dl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,Z-d dl.m/Z/  G d de      Z0 G d de      Z1e'jd                  Z3dZ4d Zd Zd Z5d Z6ddZ7d Z8 G d de      Z9y)    N)APIView)Responsestatus)
guess_type)MultiPartParser
FormParser   )extract_text_from_pdfparse_prescription_dataparse_bill_data"calculate_basic_validation_results(calculate_intelligent_validation_results#extract_text_from_image_with_gemini)AllowAny)sync_to_async)settings)JsonResponse)Image)SentenceTransformerc                   $    e Zd ZegZd Zd Zd Zy)PDFAnalysisAPIViewc                 ~
   |j                   j                  dd      j                         dk(  }|r| j                  |      S |j                  j                  d      }|j                  j                  d      }|st        dddd	t        j                  
      S |st        dddd	t        j                  
      S 	 t        |j                        \  }}|r|j                  d      rt        |      }nt        |      }t        |j                        \  }}|r|j                  d      rt        |      }	nt        |      }	|st        dddd	t        j                  
      S |	st        dddd	t        j                  
      S t        j                  j                  d      5 }
|
j!                  | j"                  |d      }|
j!                  | j"                  |	d      }|j%                         }|j%                         }|
j!                  t&        ||      }|
j!                  t(        |	|      }|j%                         }|j%                         }|
j!                  t*        ||||	      }|
j!                  t,        ||||	      }|j%                         }|j%                         }d d d        j                  dd      |j                  dd      |j                  dd      |j                  dg       |j                  dg       dj                  dd      |j                  dd      |j                  dd      |j                  dg       |j                  dg       ddj                  d d      |j                  d!d      |j                  d"d      |j                  d#d      |j                  d$d%      |j                  d&d%      |j                  d'd%      |j                  d(d%      |j                  d)d%      |j                  d*g       |j                  d+g       |j                  d,g       |j                  d-g       |j                  d.g       |j                  d/g       d0j                  d1i       |j                  d2i       |j                  d3i       |j                  d4i       |j                  d5i       |j                  d6d%      |j                  d7d8      d9d:d;}t        d<d=d>|d?t        j.                  
      S # 1 sw Y   [xY w# t0        $ r2}t        dd@t3        |      d	t        j4                  
      cY d }~S d }~ww xY w)ANis_chat trueprescription_pdfbill_pdfF  zPrescription file is requiredsuccessr   messager   zBill file is requiredimagez(Could not extract text from prescriptionz Could not extract text from bill   )max_workersprescriptionbillpatientNamez	Not found
doctorNamedatemedicationstests)r(   r)   r*   r+   r,   hospitalNamebillDatetotalAmountz$0.00)r-   r.   r/   r+   r,   )r&   r'   prescriptionValid
testsMatchmedicationsMatchamountReasonableoverallScorer   prescriptionScore
testsScoremedicationsScoreamountScorematchedMedicationsmatchedTestsunmatchedPrescriptionMedsunmatchedBillMedsunmatchedPrescriptionTestsunmatchedBillTests)r0   r1   r2   r3   r4   prescription_scoretests_scoremedications_scoreamount_scorematched_medicationsmatched_testsunmatched_prescription_medsunmatched_bill_medsunmatched_prescription_testsunmatched_bill_testsmedicalAccuracybillAccuracycrossValidationfraudDetectionrecommendationsoverallIntelligentScoresummaryzNo summary available)medical_accuracybill_accuracycross_validationfraud_detectionrM   overall_intelligent_scorerO   )prescription_analysisbill_analysis)
ocrResultsbasic_validationintelligent_validationai_analysisT   z#PDF analysis completed successfullyr!   r   r"   data  )query_paramsgetlowerhandle_chat_requestFILESr   r   HTTP_400_BAD_REQUESTr   name
startswithr   r   
concurrentfuturesThreadPoolExecutorsubmitget_ai_analysisresultr   r   r   r   HTTP_200_OK	ExceptionstrHTTP_500_INTERNAL_SERVER_ERROR)selfrequestr   prescription_file	bill_filemime_type_pres_prescription_textmime_type_bill	bill_textexecutorfuture_prescription_aifuture_bill_aiprescription_ai_analysisbill_ai_analysisfuture_prescription_datafuture_bill_dataprescription_data	bill_datafuture_basic_validationfuture_intelligent_validationbasic_validation_resultsintelligent_validation_resultsresponse_dataes                            C/var/www/html/ai-insurance-compliance-backend/pdf_analysis/views.pypostzPDFAnalysisAPIView.post   s    &&**9b9??AVK++G44 $MM--.@AMM%%j1	  : 11	3 3  2 11	3 3w	= *+<+A+A BNA.";";G"D$GHY$Z!$9:K$L! !+9>> :NA.";";G"D?	J	1)<	$ESMw x  BH  B]  B]  ^  ^ESMo py  zU  zU  V  V ##6616E X)19M9MO`bp)q&!)1E1EyRX!Y ,B+H+H+J(#1#8#8#:  ,4??;RTeg  ,A(#+???IO_#`  %=$C$C$E!,335	 +3//:\^oqz:KY+X' 19@h<MyZkmv1x- ,C+I+I+K(1N1U1U1W.7XD (9'<'<]K'X&7&;&;L+&V 1 5 5fk J'8'<'<]B'O!2!6!6w!C% )2nk(R$-MM*k$J'0}}]G'L'0}}]B'G!*w!;$ *B)E)EFY[`)a":">">|U"S(@(D(DEWY^(_(@(D(DEWY^(_$<$@$@QR$S +C*F*FGZ\]*^#;#?#?a#P)A)E)EFXZ[)\$<$@$@PQ$R+C+G+GH\^`+a%=%A%A.RT%U3K3O3OPkmo3p+C+G+GH[]_+`4L4P4PQmoq4r,D,H,HI]_a,b%%* )G(J(JK\^`(a%C%G%GXZ%[(F(J(JK\^`(a'E'I'IJZ\^'_'E'I'IJ[]_'`1O1S1STmop1q=AA)Mcd+ .F%5 _3Mj @%	
 ((* *gX Xt  	= q6 ;;	= =	=sE   :B$T  T   T  C;S4IT 4S>9T 	T<
'T71T<7T<c                     	 t        j                  d      }|dk(  rd| d}nd| d}|j                  |      }|j                  S # t        $ r}dt        |       cY d}~S d}~ww xY w)	z Get AI analysis for the documentgemini-1.5-flashr&   zv
                Analyze this prescription document and provide a detailed analysis:
                
                aT  
                
                Please provide:
                1. Patient information
                2. Doctor information
                3. Prescribed medications with dosages
                4. Prescribed tests/procedures
                5. Patient's ailment/condition
                6. Any concerns or observations
                zv
                Analyze this medical bill document and provide a detailed analysis:
                
                a@  
                
                Please provide:
                1. Hospital/clinic information
                2. Billed medications with costs
                3. Billed tests/procedures with costs
                4. Total amount breakdown
                5. Any concerns or observations about pricing
                zAI analysis failed: N)genaiGenerativeModelgenerate_contenttextrn   ro   )rq   r   document_typemodelpromptresponser   s          r   rk   z"PDFAnalysisAPIView.get_ai_analysis   s    #	3))*<=E.  	   --f5H==  	3)#a&22	3s   AA 	A'A"A'"A'c           	         	 |j                   j                  dd      j                         }|st        ddddt        j
                        S t        j                  d      }|j                  |      }t        d	d
d||j                  dddt        j                        S # t        $ rI}t        j                         }t        dddt        |       dt        j                        cY d}~S d}~ww xY w)z/Handle chat requests with direct AI interactionr   r   Fr   z$Prompt is required for chat requestsr    r   r   Tr[   z$Chat response generated successfullyz2025-06-17T09:25:20Z)r   r   	timestampr\   r^   zChat request failed: N)r]   r`   stripr   r   rd   r   r   r   r   rm   rn   	traceback
format_excro   rp   )rq   rr   r   r   r   r   traceback_strs          r   rb   z&PDFAnalysisAPIView.handle_chat_request   s    !	=\\%%h399;F$!E! !55	7 7 ))*<=E--f5HA$ (!7		 ((	* 	*  	=%002M 23q6(; ;;	= =	=s%   A
B! AB! !	C3*>C.(C3.C3N)__name__
__module____qualname__r   permission_classesr   rk   rb        r   r   r      s    "Q=f%3N#=r   r   c                       e Zd Zd Zy)PDFAnalysisHistoryViewc                     	 t        dddg dt        j                        S # t        $ r2}t        ddt	        |      dt        j
                        cY d }~S d }~ww xY w)	NTr[   z%Analysis history fetched successfullyr\   r   Fr^   r    )r   r   rm   rn   ro   rp   )rq   rr   r   s      r   r`   zPDFAnalysisHistoryView.get  sl    	=B	
 ((* *  	= q6 ;;	= =	=s   " 	A'AAAN)r   r   r   r`   r   r   r   r   r      s    =r   r   zThttps://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContentc                 :   | j                         }t        j                  |      j                  d      }ddddidd|digigi}t	        j
                  t         d	t         |
      }|j                          |j                         }|d   d   d   d   d   d   S )Nzutf-8contentspartsr   zEExtract all text clearly and completely from this prescription image.inline_data
image/jpeg)	mime_typer]   z?key=json
candidatesr   content)
readbase64	b64encodedecoderequestsr   GEMINI_VISION_URLGEMINI_API_KEYraise_for_statusr   )
image_file	img_bytes
img_base64payloadrespr]   s         r   r   r     s    !I!!),33G<J 	`a!%1 *$

 
G ==
U>"23D 	99;Da +G4Q7??r   c                    | j                         }t        j                  |d      }d}|D ]  }|j                         }t	        j                  t        j                  |j                  d                  }t        j                         }|j                  |d       |j                  d       |t        |      dz   z  } |j                         S )	Npdf)streamfiletyper   pngJPEG)formatr   
)r   fitzopen
get_pixmapr   ioBytesIOtobytessaveseekr   r   )pdf_file	pdf_bytespdf_doc	full_textpagepiximgbufs           r   r   r   2  s    Iiiy59GI EoojjCKK$678jjlV$8=DD	E ??r   c                    | j                  d      D cg c]#  }|j                         s|j                         % }}d d d d d d d d g g d d d}|r|d   |d<   t        |      D ]x  \  }}t        j                  d|t        j
                        r||d<   t        j                  d|t        j
                        r%|j                  d      d	   j                         |d<   t        j                  d
|t        j
                        r%|j                  d      d	   j                         |d<   t        j                  d|t        j
                        r`|j                  d      d	   j                         }d|v r:|j                  d      \  }}|j                         |d<   |j                         |d<   t        j                  d|t        j
                        r%|j                  d      d	   j                         |d<   t        j                  d|t        j
                        r%|j                  d      d	   j                         |d<   t        j                  d|      r|j                  d      }|d   j                  dd      d   j                         }	t        |      dkD  r|d   j                         nd }
t        j                  d|	t        j
                        }|r|j                  d      nd }|r |	j                  |d      j                         n|	}d|i}|r||d<   |
r|
|d<   |d   j                  |       t        j                  d|      r2|d   j                  |j                  d d      j                                t        j                  d!|      s2|j                         |d"<   d#|v sKd$|v sQt        j                  d%|      j                  d      |d&<   { |S c c}w )'Nr   )hospital_nameaddressphonepatient_nameagegender	diagnosisr*   	medicinesdoctor_advicedoctor_namespecializationr   r   zstreet|road|indiar   r   :zPatient Namer   z
Age/Gender/r   r   	Diagnosisr   Dater*   z\d+\.z - .r
   z	(\d+mg.*)r   re   dose	frequencyr   u   ^•r   u   •zDr\.r   ()z	\((.*?)\)r   )splitr   	enumerateresearch
IGNORECASEmatchlengroupreplaceappend)r   linelinesr]   iagr   r   	med_partsmed_name_dosemed_freq
dose_matchr   re   med_objs                  r    format_prescription_text_to_jsonr   @  sE   &*jj&6Gd$**,TZZ\GEG D   %a_U# $P499)4?"DO99XtR]]3 JJsOB/557DM99_dBMM:#'::c?2#6#<#<#>D 99]D"--8C$**,Bby hhsmV!iikU!'X99\47 $

3 3 9 9 ;D99WdBMM2::c?2.446DL88Hd#

5)I%aL..sA6q9??AM/29~/Ay|))+tH<NJ*4:##A&$D>B=((r288:DtnG"&'/$$$W-99Wd#!((eR)@)F)F)HI99Wd#"&**,Dd{sd{)+<)F)L)LQ)O%&I$PL Ku Hs
   O O c                     d|  d}ddd|igigi}t        j                  dt         |      }|j                          |j	                         }|d   d	   d
   d   d	   d   S )Nz
You are a professional medical AI assistant. 
Analyze the following prescription and return the result ONLY in valid JSON format.

Prescription:
a  

JSON Structure to return:
{
    "is_safe": true/false,
    "doctor_analysis": "Detailed technical analysis for medical professionals.",
    "safety_check": "Summary of dosage correctness, drug interactions, and monitoring requirements.",
    "patient_summary": "Simple, patient-friendly explanation of treatment plan.",
    "issues": ["List of potential problems."],
    "suggestions": ["List of recommendations or precautions."]
}

Rules:
- Respond ONLY with raw JSON (no extra commentary, no markdown, no triple backticks).
- Use proper boolean values for is_safe.
- If data is missing (e.g., patient weight, renal function), mention it under issues.
- Do not include any formatting like ```json or ``` in your response.
r   r   r   zYhttps://generativelanguage.googleapis.com/v1/models/gemini-1.5-flash:generateContent?key=r   r   r   r   )r   r   r   r   r   )r   r   r   r   r]   s        r   gemini_text_analysisr     s    
  F2 	vv&'
 G ==
cdrcstD 	99;Da +G4Q7??r   c                    t         j                  j                  t        j                  d      }t         j                  j                  t        j                  d      }t        d      }t        j                  |      }t        |d      5 }t        j                  |      }d d d        |j                  | g      }|j                  t        j                  |      |      \  }	}
|
d   D cg c]  }|   	 c}S # 1 sw Y   YxY wc c}w )Nzfaiss_index.binz	texts.pklzall-MiniLM-L6-v2rbr   )ospathjoinr   EMBEDDING_DIRr   faiss
read_indexr   pickleloadencoder   nparray)querytop_kfaiss_index_path
texts_pathr   indexftextsquery_embedding	distancesindicesr   s               r   get_similar_chunksr    s    ww||H$:$:<MNh44kBJ 23E-.E	j$	 1AllE7+Obhh&?GIw%aj)E!H))	  *s   	C7(D7D c                    d| j                  d       d| j                  d       d| j                  d       d| j                  d       d	d
j                  | j                  dg       D cg c]  }|d   	 c}       
}t        |d      }t               }|D ]E  }|j	                  d      D ]/  }|j                  |j                         j                                1 G t        | j                  dg       D cg c]#  }|d   j                         j                         % c}      }t        ||z
        t        ||z
        d}||dS c c}w c c}w )Nz	Patient: r   z, Age: r   z
, Gender: r   z, Diagnosis: r   z, Medicines: z, r   re      )r  r  ,)not_in_faissextra_in_faiss)faiss_contextmedicine_comparison)	r`   r  r  setr   addr   ra   list)	structured_datamr  chunks
faiss_medschunkwordai_meds
mismatchess	            r   analyze_prescription_with_faissr)    s   ++N;<GODWDWX]D^C__ijyj}j}  G  kH  jI  IV  Wf  Wj  Wj  kv  Ww  Vx  xE  FJ  FO  FO  ds  dw  dw  xC  EG  dH  PI  _`  QR  SY  QZ  PI  FJ  EK  LEe15F J 1KK$ 	1DNN4::<--/0	11
 o6I6I+WY6Z[1V9??$**,[\GWz12zG34J  ) # PI \s   )E	8(Ec                        e Zd ZegZeefZd Zy)PrescriptionAnalysisAPIViewc                 F   |j                   j                  d      }|st        ddid      S |j                  }|dv rt	        |      }n |dk(  rt        |      }nt        ddid      S t        |      }t        |      }|j                         }|j                  d	      r3|j                  d
      }|j                  dd      j                  dd      }	 t        j                  |      }t        |      }	t        |||	d      S # t        $ r t        ||ddd      cY S w xY w)NfileerrorzNo file uploadedr   r   )r   z	image/pngz	image/jpgzapplication/pdfzUnsupported file typez````zjson
r   zjson
zAI did not return valid JSON)rW   ai_analysis_rawr.  r^   )rW   analysisfaiss_analysis)rc   r`   r   content_typer   r   r   r   r   rf   r   r   loadsrn   r)  )
rq   rr   r-  r   extracted_textstructured_ocrai_rawcleanedai_json
faiss_datas
             r   r   z PrescriptionAnalysisAPIView.post  s5   }}  (*< =cJJ%%	@@@FN++248N*A B3OO9.I%n5 ,,.e$mmC(Gooh3;;JKG	jj)G 5^D
((
  	  	,#)7! 	 	s   D D D N)	r   r   r   r   r   r   r	   parser_classesr   r   r   r   r+  r+    s    "%z2N'r   r+  )r  ):r   r   r   r   r   r   r   r  r  r  rest_framework.viewsr   rest_framework.responser   rest_frameworkr   	mimetypesr   rest_framework.parsersr   r	   utilsr   r   r   r   r   r   rest_framework.permissionsr   asyncioconcurrent.futuresrg   asgiref.syncr   google.generativeaigenerativeair   django.confr   django.httpr   PILr   numpyr
  sentence_transformersr   r   r   GOOGLE_API_KEYr   r   r   r   r  r)  r+  r   r   r   <module>rN     s    I I I I I ( , !   >  0   & #   $   5a= a=H=W =, ((j @4;@%@P	*0+' +r   