o
    di,                     @   s   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 d dl	m
Z
 d dlmZ ejejd e
  e ddZe d	d
Ze ddZejdeeedZdZdddZdS )    N)BotoCoreErrorClientError)get_db_connection)load_dotenv)send_message)levelAWS_ACCESS_KEY_IDAKIAUWPMKLMSH5E4QMNYAWS_SECRET_ACCESS_KEYz(DgvVy4lGJfRyX689uzZXGVpFyo+S6Qx392M8tUpb
AWS_REGIONz
eu-north-1zbedrock-runtime)service_nameregion_nameaws_access_key_idaws_secret_access_keyzamazon.nova-lite-v1:0c                 C   sp  t  }| }|r| d}| d}nd}d}|d| d| f | }|D ]}|d }td|  d	|r>|d d
 nd d |rL| dkrUtd|   q)d| d}	td|  d	|	  dddddd|	igdgd}
ztdt	|
  t
jtddt	|
d}|d  d}td|  d	|  d}|rt|}|d i d!i d"g }|rt|tr|d# dd }|std$|   td%|  |d&r|d&dd'd }n|d'r|d'd }| }td(|  d	|  zt|}W n$ tjy5 } ztd)|  d	t|  td*|   d }~ww t	|d+g }t	|d,g }t	|d-g }|d.d}|d/d}t	|d0i }|d1d}|d2d}|d3p|d4pi }t	|}t	|d5g }t	|d6i }|d6i d7d}td8|  d9| d:| d;| d<| d=| d>| d?| d@| dA| dB| dC| dD|  |dE| dF||||||||||||||| f |  t| | tdG|   W q) tttjtfy- } z#tdH|  d	t|  tdId"t v r|ndJ  W Y d }~q)d }~ww |  |  d S )KN_sarvamresponse_calls7987_sarvamresponse
7987_callszSELECT * FROM z! WHERE callid = %s AND status = 1   u%   🔍 Retrieved transcript for callid z: d   Nonez... u+   ⚠️ Empty or null transcript for callid u  
                        Analyze the following customer call transcript and return the following in JSON format:
                        1. Top 5 Keywords
                        2. Overall Sentiment with all (Positive, Negative, Neutral) with percentage 
                        3. Detected Emotions (e.g., Happy, Angry, Frustrated)
                        4. Summary of the Call
                        5. Sales Intent (High, Medium, Low)
                        6. Customer Details (name, phone, email if available)
                        7. Call Purpose / Issue Type 
                        8. Call Outcome (Resolved, Partially Resolved, Escalated, Follow-up Needed, Unresolved)
                        9. Action Items for Agent and Customer (clear and actionable)
                        10. Customer Pain Points (specific problems expressed)
                        11. Quality of the Call:
                            - Communication clarity (agent & customer)
                            - Background noise or call quality issues
                            - Long pauses or hold time
                            - Interruptions / speaking over each other
                            - Agent professionalism, politeness, and empathy
                            - Overall pacing and structure
                            - Provide a Call Quality Score (1–100)
                            - Include a brief explanation for the score

                        Transcript:
                        "z"  
                    zSending prompt for callid i  gffffff?g?)max_new_tokenstemperaturetop_pusertext)rolecontent)inferenceConfigmessageszRequest body: zapplication/json)modelIdcontentTypeacceptbodyr$   zutf-8zRaw response body for callid outputmessager   r   z"Empty content received for callid z8Empty content received from Bedrock response for callid z```jsonz```z$Cleaned response content for callid zJSON decode error for callid zInvalid content: zTop 5 KeywordszOverall SentimentzDetected EmotionszSummary of the CallzSales IntentzCustomer DetailszCall Purpose / Issue TypezCall Outcomez#Action Items for Agent and CustomerzAction ItemszCustomer Pain PointszQuality of the CallzCall Quality ScorezParsed data for callid z: Keywords: z, Sentiment: z, Emotions: z, Summary: z	, Sales: z, Customer: z,Call Purpose: z,Call Outcome: z,Action Items: z,Pain Points: z,Call Quality: z,Call Quality Score: z
            UPDATE a   SET
            status = 2,
            keywords = %s,
            sentiments = %s,
            emotions = %s,
            summary = %s,
            sand_logic_response = %s,
            sales_intent = %s,
            transcripts = %s,
            customer_details = %s,
            call_purpose = %s,
            call_outcome = %s,
            action_items = %s,
            pain_points = %s,
            call_quality = %s,
            call_quality_score = %s
            WHERE callid = %s
            u   ✅ Bedrock processed callid u   ❌ Bedrock error for callid u   ⚠️ Failed content: zNo content available)r   cursorexecutefetchalllogginginfostripwarningjsondumpsbedrockinvoke_modelMODEL_IDreaddecodeloadsget
isinstancelisterror
ValueError
startswithreplaceJSONDecodeErrorstrcommitr   r   r   localsclose)call_idbidconnr'   sarvam_response_tablecalls_tablecallscall
transcriptpromptr$   responseraw_responser   response_bodycontent_listparsedekeywords	sentimentemotionssummarysalesintentcustomer_detailscall_purposecall_outcomeaction_items_dataaction_itemspain_pointscall_qualitycall_quality_score r^   9/home/aiteam/pcaa-dev/post call analysis/openai_helper.pysend_openai_analysisy   s   

(



X
,r`   )N)osr.   r*   boto3botocore.exceptionsr   r   	db_configr   dotenvr   message_helperr   basicConfigINFOgetenvr   r
   r   clientr0   r2   r`   r^   r^   r^   r_   <module>   s*   ^