o
    iq&                     @   sR  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mZ d dlm	Z	m
Z
mZ d dlZd dlmZ d dlmZ d dlmZmZmZmZmZmZ d dlmZmZ d dlmZ d d	lmZ d d
l m!Z! e	 Z"ej#ej$dZ%eej&dZ'eej(Z)edde)dZ*e Z+G dd de+Z,G dd de+Z-dZ.dZ/e"0dde
de1de1fddZ2dS )    N)datetimetimezone)	APIRouter	WebSocketWebSocketDisconnect)Voice)AsyncElevenLabs)create_engineColumnStringIntegerTextDateTime)declarative_basesessionmaker)UUID)settings)search_knowledge_base)api_keyF)
autocommit	autoflushbindc                   @   s6   e Zd ZdZeeddddZeedZee	Z
dS )ProjectSummaryprojectsTas_uuid)primary_keyd   N)__name__
__module____qualname____tablename__r
   pg_UUIDidr   voice_idr   test_duration_seconds r&   r&   -/var/www/html/voicebot/backend/call_engine.pyr      s
    r   c                   @   s   e Zd ZdZeedddejdZeeddZ	eeddZ
eedddd dZeeZeeZeed	ZeeZeeZeeddd
d dZdS )TestReportSummarytest_reportsTr   )r   default)r   c                   C      t tjS Nr   nowr   utcr&   r&   r&   r'   <lambda>(       zTestReportSummary.<lambda>)r*   2   c                   C   r+   r,   r-   r&   r&   r&   r'   r0   .   r1   N)r   r   r    r!   r
   r"   uuiduuid4r#   user_id
project_idr   test_date_timer   duration_secondsratingr   ai_statement_shortr   ai_statement_fullrecording_path
created_atr&   r&   r&   r'   r(   #   s    r(   a  You are a CUSTOMER calling a business.
The person you are speaking to is the CUSTOMER SERVICE AGENT.
STRICT RULES:
1. YOU ARE THE CUSTOMER. Never act like the agent. Do not offer to help.
2. Never output prefixes like "Customer:" or "Agent:". Just say the words you want to speak.
3. Use the Knowledge Base below to ask natural questions. 
4. Be brief (1-2 sentences).

KNOWLEDGE BASE:
{knowledge_base}
a  You are an expert QA evaluator for call centers. Review the following call transcript where a human AGENT is speaking to an AI CUSTOMER.
Provide a JSON response with the following keys:
1. "rating": An integer from 1 to 10 evaluating the HUMAN AGENT's performance.
2. "quality_tag": A short 2-3 word tag (e.g., "Rude", "Helpful", "Lacked Knowledge").
3. "problem_statement": A text string explaining what the agent did well and what they did wrong.
Transcript:
{transcript}
z/ws/call/{project_id}/{user_id}	websocketr6   r5   c           (         sv  |   I d H  t }z7z#|ttj|k }|r"|jr"|jnd}|r,|jr,|jnd}W n t	y<   d}d}Y nw W |
  n|
  w g }g }t }	|d }
d}d }d}z	 t |	 }||
kr{z| dddI d H  W n   Y nxztj|  d	d
I d H }W n
 tjy   Y q\w |ddkr|rq\d}z|d}d|vr|d|  |dd| d z{t||}td|}d|dg| }tjjjd|dI d H }|jd jj}|dd dd  }|sd}tj |t!|ddddI d H }|2 z3 d H W }| "|I d H  q6 | ddiI d H  |d|d d|vr8|d |  W n? t#yF   Y W d}n t	yx } z&z| d!d"t$| d#I d H  W n   Y W Y d }~W d}nW Y d }~nd }~ww W d}nud}w |dd$krzD|d%}|rt%&  d&}t'j()d'd(|}t'j*t'j(+|dd) t,|d*}|-t./| W d    n	1 sw   Y  |}W n% t	y } zt0d+|  W Y d }~nd }~ww |dd,krd}nq]W n# t#y   Y n t	y } zt0d-|  W Y d }~nd }~ww t1t |	 }d.)|} |  s,d/} z|rBz| d0d1d2I d H  W n   Y tjjjdd3d4idd5ddt2d6| dgd7I d H }!t34|!jd jj}"|"d8d9}#t5|#t6r~d:)d;d< |#D }#nt$|#}#|# d=|  }$t }zLz+t7||t89t:j;|t1|"d>dt$|"d?d9d d@ |$|dA}%|<|% |=  W n t	y }& zt0dB|&  W Y d }&~&nd }&~&ww W |
  n|
  w |rz| ddCiI d H  | 
 I d H  W W d S    Y W d S W d S  t	y: }' z-t0dD|'  |r(z	| 
 I d H  W n   Y W Y d }'~'d S W Y d }'~'d S W Y d }'~'d S d }'~'ww )ENEXAVITQu4vr4xnSDxMaL      FT
call_endedduration_reached)eventreasong       @)timeoutrD   user_speech_texttextz(Agent is silentzAgent (Human): userzAgent says: )rolecontentz{knowledge_base}systemzgpt-4o)modelmessagesr   zAgent:z	Customer:zCould you clarify that?)r$   eleven_turbo_v2)rH   voicerM   streamai_speech_complete	assistantzCustomer (AI): errorz
AI Error: )rD   messageaudio_upload	audio_b64z_recording.webmuploads
recordings)exist_okwbzWS Audio Save Error: end_callzWebSocket Error: 
z(No conversation took place)status_update
evaluating)rD   steptypejson_objectz!You are a JSON outputting QA bot.z{transcript})rM   response_formatrN   problem_statementzN/A c                 s   s    | ]}t |V  qd S r,   )str).0itemr&   r&   r'   	<genexpr>   s    z&voice_call_endpoint.<locals>.<genexpr>z

--- TRANSCRIPT ---
r9   quality_tagr2   )r5   r6   r7   r8   r9   r:   r;   r<   zDB Save Error: evaluation_completezEval Error: )>acceptSessionLocalqueryr   filterr#   firstr$   r%   	Exceptionclosetime	send_jsonasynciowait_forreceive_jsonTimeoutErrorgetappendr   SYSTEM_PROMPTreplaceopenai_clientchatcompletionscreatechoicesrU   rK   splitstripeleven_clientgenerater   
send_bytesr   rf   r3   r4   ospathjoinmakedirsdirnameopenwritebase64	b64decodeprintintEVALUATION_PROMPTjsonloads
isinstancelistr(   r   r.   r   r/   addcommit)(r>   r6   r5   dbproject_dataactive_voice_idtarget_durationchat_historyfull_transcript
start_timemax_durationis_generatingr<   call_ended_gracefullyelapsed_timedata	user_text
kb_contextcurrent_sys_promptrN   text_responseai_response_textaudio_streamaudio_chunkai_errrW   	file_name	file_pathf
upload_erredurationtranscript_texteval_response	eval_dataraw_problemfinal_statement
new_reportdb_erreval_errr&   r&   r'   voice_call_endpointE   sB  


&
R

"


r   )3r   ru   rs   r   r   r3   r   r   fastapir   r   r   openai
elevenlabsr   elevenlabs.clientr   
sqlalchemyr	   r
   r   r   r   r   sqlalchemy.ormr   r   sqlalchemy.dialects.postgresqlr   r"   configr   rag_managerr   routerAsyncOpenAIOPENAI_API_KEYr}   ELEVENLABS_API_KEYr   DATABASE_URLenginerm   Baser   r(   r{   r   r>   rf   r   r&   r&   r&   r'   <module>   s8     
	