o
    Si	                     @   s  U 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mZmZ ejejd edZdZdZe
 Zdd	d
ddddddddddddddddddddddd dd!d"d#d$d%d&d'd(dd)d*d+d,d-d.d/d0dd1d2d3d4d5d6d7d8dd9d:d;d<d=d>d?d@ddAdBddCdDdEdFdGddHdIdJdKdLdMdNdOddPdQdRdSdTdUdVdWddXdYdZd[d\d]d^d_dd`dadbdcdddedfdgddhZeeeeef f edi< djZee Zdkee dleeef fdmdnZ doedlefdpdqZ!dredlefdsdtZ"ddredkee dleeef fdudvZ#dredleeef fdwdxZ$		ddyedzed{ed|ee dkee dleeef fd}d~Z%e&dkrrd dl'Z'd dl(Z(e'j)de'j*dZ+e+j,dedd e+j,dedd e+j,dedd e+j,deddd e+j,deeede d e+j,dedd e+- Z.e.j/e.j0e.j1e.j2e.j3f\Z4Z5Z6Z7Z8e.j9r zHe.j9Z:e j;<e:re=e:ddZ>e?e>Z@W d   n	1 sw   Y  neAe:Z@e@BdyZ4e@BdZ5e@BdZ6e@BdZ7e@BdkeZ8W n eCy ZD zeEdeD  e(Fd W Y dZD[DndZD[Dww e4r	e5r	e6seEd dZ4dZ5dZ6dZ7dZ8eEd eEde  eEde8  eEde4  eEde6dd  eGe6dkrAdnd  e7rUeEde7dd  d eEd e%e4e5e6e7e8dZHeEd eEejIeHddd dS dS )    N)AudioSegment)DictAnyOptional)levelresponse_iq_analysisz#http://localhost:11434/api/generatez
qwen2.5:7bEnglishzEnglish (Latin script)en-INu   Write ALL analysis fields — comparison, behavioralAnalysis, tonalAnalysis — entirely in English. The 'visuals' keywords must also be in English.zVoice Tonal Metadata:u   Stat interpretation guide — Low pitch_std = monotone delivery; High energy_fluctuation = shaky/hesitant voice; High avg_flatness = breathy or unclear articulation; Moderate tempo = confident and composed delivery.zSince no voice metadata is available, base the tonal analysis on the written tone of the answer (e.g., formal, casual, assertive, apologetic).z03 single English words or short English phrases.)display_namescript_namespeech_localeresponse_instructionaudio_context_header
audio_hinttext_tone_fallbackvisuals_instructionHindiu.   Hindi (Devanagari script / हिन्दी)zhi-INu]  The question, ideal answer, and user's answer are all in Hindi (Devanagari script). You MUST write ALL analysis fields — comparison, behavioralAnalysis, tonalAnalysis — entirely in Hindi using Devanagari script. Do NOT mix English sentences inside the analysis fields. Technical terms may be kept in English only when no Hindi equivalent exists.uT   आवाज़ की टोनल मेटाडेटा (Voice Tonal Metadata):u  स्टैट्स की व्याख्या — कम pitch_std = एकरस/नीरस आवाज़; अधिक energy_fluctuation = कंपकंपाती या हिचकिचाती आवाज़; अधिक avg_flatness = सांसयुक्त या अस्पष्ट उच्चारण; मध्यम tempo = आत्मविश्वासपूर्ण और संयमित बोलने का तरीका।ud  चूँकि कोई आवाज़ मेटाडेटा उपलब्ध नहीं है, टोनल विश्लेषण उत्तर की लिखित भाषा-शैली के आधार पर करें (जैसे — औपचारिक, अनौपचारिक, दृढ़, विनम्र)।u   3 हिंदी शब्द या छोटे हिंदी वाक्यांश जो उत्तर का समग्र भाव दर्शाएं।Marathiu-   Marathi (Devanagari script / मराठी)zmr-INuc  The question, ideal answer, and user's answer are all in Marathi (Devanagari script). You MUST write ALL analysis fields — comparison, behavioralAnalysis, tonalAnalysis — entirely in Marathi using Devanagari script. Do NOT mix English sentences inside the analysis fields. Technical terms may be kept in English only when no Marathi equivalent exists.uS   आवाजाचे टोनल मेटाडेटा (Voice Tonal Metadata):u  स्टॅट्सचा अर्थ — कमी pitch_std = एकसुरी/नीरस आवाज; जास्त energy_fluctuation = थरथरणारा किंवा अडखळणारा आवाज; जास्त avg_flatness = श्वासयुक्त किंवा अस्पष्ट उच्चार; मध्यम tempo = आत्मविश्वासपूर्ण आणि संयमित बोलण्याची पद्धत।uH  कारण कोणताही आवाज मेटाडेटा उपलब्ध नाही, टोनल विश्लेषण उत्तराच्या लिखित शैलीवर आधारित करा (उदा. औपचारिक, अनौपचारिक, ठाम, नम्र).u   3 मराठी शब्द किंवा छोटे मराठी वाक्यांश जे उत्तराचा एकूण भाव दर्शवतात.Tamilu&   Tamil (Tamil script / தமிழ்)zta-INuS  The question, ideal answer, and user's answer are all in Tamil (Tamil script). You MUST write ALL analysis fields — comparison, behavioralAnalysis, tonalAnalysis — entirely in Tamil using Tamil script. Do NOT mix English sentences inside the analysis fields. Technical terms may be kept in English only when no Tamil equivalent exists.u\   குரல் டோனல் மெட்டாடேட்டா (Voice Tonal Metadata):u[  புள்ளிவிவர விளக்கம் — குறைந்த pitch_std = ஒரே சுரத்தில் பேசும் முறை; அதிக energy_fluctuation = நடுங்கும் அல்லது தயங்கும் குரல்; அதிக avg_flatness = மூச்சுக்காற்று கலந்த அல்லது தெளிவற்ற உச்சரிப்பு; மிதமான tempo = தன்னம்பிக்கையான மற்றும் அமைதியான பேச்சு முறை.u  குரல் மெட்டாடேட்டா இல்லாததால், டோனல் பகுப்பாய்வை எழுதப்பட்ட பதிலின் தொனியை அடிப்படையாகக் கொண்டு செய்யவும் (எ.கா. அலுவல்முறை, சாதாரண, உறுதியான, பணிவான).u   3 தமிழ் வார்த்தைகள் அல்லது சிறிய தமிழ் சொற்றொடர்கள் பதிலின் ஒட்டுமொத்த தன்மையை விவரிக்கும்.Teluguu+   Telugu (Telugu script / తెలుగు)zte-INuX  The question, ideal answer, and user's answer are all in Telugu (Telugu script). You MUST write ALL analysis fields — comparison, behavioralAnalysis, tonalAnalysis — entirely in Telugu using Telugu script. Do NOT mix English sentences inside the analysis fields. Technical terms may be kept in English only when no Telugu equivalent exists.uS   వాయిస్ టోనల్ మెటాడేటా (Voice Tonal Metadata):u  గణాంక వివరణ — తక్కువ pitch_std = ఏకస్వర పద్ధతిలో మాట్లాడటం; అధిక energy_fluctuation = వణికే లేదా సంకోచించే స్వరం; అధిక avg_flatness = శ్వాసతో కూడిన లేదా అస్పష్టమైన ఉచ్చారణ; మధ్యస్థ tempo = ఆత్మవిశ్వాసంతో మరియు స్థిరంగా మాట్లాడడం.uz  వాయిస్ మెటాడేటా అందుబాటులో లేనందున, టోనల్ విశ్లేషణను రాసిన సమాధానం యొక్క శైలి ఆధారంగా చేయండి (ఉదా. అధికారిక, అనధికారిక, నిర్ణయాత్మక, వినయంగా).u   3 తెలుగు పదాలు లేదా చిన్న తెలుగు పదబంధాలు సమాధానం యొక్క మొత్తం భావాన్ని వ్యక్తం చేసేవి.Kannadau*   Kannada (Kannada script / ಕನ್ನಡ)zkn-INu]  The question, ideal answer, and user's answer are all in Kannada (Kannada script). You MUST write ALL analysis fields — comparison, behavioralAnalysis, tonalAnalysis — entirely in Kannada using Kannada script. Do NOT mix English sentences inside the analysis fields. Technical terms may be kept in English only when no Kannada equivalent exists.uP   ಧ್ವನಿ ಟೋನಲ್ ಮೆಟಾಡೇಟಾ (Voice Tonal Metadata):u  ಅಂಕಿ-ಅಂಶಗಳ ವಿವರಣೆ — ಕಡಿಮೆ pitch_std = ಏಕತಾನ ಮಾತಿನ ರೀತಿ; ಹೆಚ್ಚು energy_fluctuation = ನಡುಗುವ ಅಥವಾ ಅಳುಕುವ ಧ್ವನಿ; ಹೆಚ್ಚು avg_flatness = ಉಸಿರು ಸೇರಿದ ಅಥವಾ ಅಸ್ಪಷ್ಟ ಉಚ್ಚಾರಣೆ; ಮಧ್ಯಮ tempo = ಆತ್ಮವಿಶ್ವಾಸದಿಂದ ಮತ್ತು ಸ್ಥಿರವಾಗಿ ಮಾತನಾಡುವ ರೀತಿ.uJ  ಧ್ವನಿ ಮೆಟಾಡೇಟಾ ಲಭ್ಯವಿಲ್ಲದ ಕಾರಣ, ಟೋನಲ್ ವಿಶ್ಲೇಷಣೆಯನ್ನು ಬರೆದ ಉತ್ತರದ ಶೈಲಿಯ ಆಧಾರದ ಮೇಲೆ ಮಾಡಿ (ಉದಾ. ಔಪಚಾರಿಕ, ಅನೌಪಚಾರಿಕ, ದೃಢ, ವಿನಮ್ರ).u   3 ಕನ್ನಡ ಪದಗಳು ಅಥವಾ ಚಿಕ್ಕ ಕನ್ನಡ ಪದಗುಚ್ಛಗಳು ಉತ್ತರದ ಒಟ್ಟಾರೆ ಭಾವವನ್ನು ಅಭಿವ್ಯಕ್ತಿಸುವ.Punjabiu.   Punjabi (Gurmukhi script / ਪੰਜਾਬੀ)zpa-INu_  The question, ideal answer, and user's answer are all in Punjabi (Gurmukhi script). You MUST write ALL analysis fields — comparison, behavioralAnalysis, tonalAnalysis — entirely in Punjabi using Gurmukhi script. Do NOT mix English sentences inside the analysis fields. Technical terms may be kept in English only when no Punjabi equivalent exists.uT   ਆਵਾਜ਼ ਦਾ ਟੋਨਲ ਮੈਟਾਡੇਟਾ (Voice Tonal Metadata):u  ਅੰਕੜਿਆਂ ਦੀ ਵਿਆਖਿਆ — ਘੱਟ pitch_std = ਇੱਕਸੁਰੀ ਬੋਲਣ ਦਾ ਢੰਗ; ਵੱਧ energy_fluctuation = ਕੰਬਦੀ ਜਾਂ ਝਿਜਕਦੀ ਆਵਾਜ਼; ਵੱਧ avg_flatness = ਸਾਹ ਭਰੀ ਜਾਂ ਅਸਪੱਸ਼ਟ ਉਚਾਰਨ; ਦਰਮਿਆਨੀ tempo = ਆਤਮਵਿਸ਼ਵਾਸ ਨਾਲ ਅਤੇ ਸੰਜਮ ਨਾਲ ਬੋਲਣਾ।u`  ਕਿਉਂਕਿ ਕੋਈ ਆਵਾਜ਼ ਮੈਟਾਡੇਟਾ ਉਪਲਬਧ ਨਹੀਂ ਹੈ, ਟੋਨਲ ਵਿਸ਼ਲੇਸ਼ਣ ਲਿਖਤੀ ਜਵਾਬ ਦੀ ਭਾਸ਼ਾ-ਸ਼ੈਲੀ ਦੇ ਆਧਾਰ 'ਤੇ ਕਰੋ (ਜਿਵੇਂ — ਰਸਮੀ, ਗੈਰ-ਰਸਮੀ, ਦ੍ਰਿੜ੍ਹ, ਨਿਮਰ)।u   3 ਪੰਜਾਬੀ ਸ਼ਬਦ ਜਾਂ ਛੋਟੇ ਪੰਜਾਬੀ ਵਾਕਾਂਸ਼ ਜੋ ਜਵਾਬ ਦੇ ਸਮੁੱਚੇ ਭਾਵ ਨੂੰ ਦਰਸਾਉਂਦੇ ਹੋਣ।Hinglishz3Hinglish (mix of Hindi and English in Latin script)uC  The question, ideal answer, and user's answer are in Hinglish (a mix of Hindi and English written in Latin script). You MUST write ALL analysis fields — comparison, behavioralAnalysis, tonalAnalysis — entirely in Hinglish using Latin script. Do NOT write in Devanagari script. Use conversational, professional Hinglish.uN   Voice Tonal Metadata (आवाज़ की टोनल जानकारी):u   Stats interpretation — कम pitch_std = monotone/एकरस delivery; high energy_fluctuation = shaky/hesitant voice; high avg_flatness = breathy/अस्पष्ट articulation; moderate tempo = confident/संयमित delivery.zSince no voice metadata is available, base the tonal analysis on the written tone of the answer (e.g. formal, casual, confident, polite) but write the analysis in Hinglish.zF3 Hinglish words or short Hinglish phrases capturing the overall vibe.Bengaliu*   Bengali (Bengali script / বাংলা)zbn-INu]  The question, ideal answer, and user's answer are all in Bengali (Bengali script). You MUST write ALL analysis fields — comparison, behavioralAnalysis, tonalAnalysis — entirely in Bengali using Bengali script. Do NOT mix English sentences inside the analysis fields. Technical terms may be kept in English only when no Bengali equivalent exists.uP   ভয়েস টোনাল মেটাডেটা (Voice Tonal Metadata):u  পরিসংখ্যানের ব্যাখ্যা — কম pitch_std = একঘেয়ে কথা বলার ধরন; বেশি energy_fluctuation = কাঁপানো বা দ্বিধাগ্রস্ত কণ্ঠস্বর; বেশি avg_flatness = শ্বাসযুক্ত বা অস্পষ্ট উচ্চারণ; মাঝারি tempo = আত্মবিশ্বাসী এবং সংযত কথা বলার ধরন।uv  যেহেতু কোনো ভয়েস মেটাডেটা উপলব্ধ নেই, তাই টোনাল বিশ্লেষণ উত্তরের লিখিত শৈলীর ওপর ভিত্তি করে করুন (যেমন আনুষ্ঠানিক, অনানুষ্ঠানিক, দৃঢ়, নম্র)।u   ৩টি বাংলা শব্দ বা ছোট বাংলা বাক্যাংশ যা উত্তরের সামগ্রিক ভাব প্রকাশ করে।Gujaratiu2   Gujarati (Gujarati script / ગુજરાતી)zgu-INub  The question, ideal answer, and user's answer are all in Gujarati (Gujarati script). You MUST write ALL analysis fields — comparison, behavioralAnalysis, tonalAnalysis — entirely in Gujarati using Gujarati script. Do NOT mix English sentences inside the analysis fields. Technical terms may be kept in English only when no Gujarati equivalent exists.uP   અવાજની ટોનલ મેટાડેટા (Voice Tonal Metadata):u  આંકડાકીય સમજૂતી — ઓછું pitch_std = એકરસ બોલવાની રીત; વધુ energy_fluctuation = ધ્રૂજતો કે અચકાતો અવાજ; વધુ avg_flatness = શ્વાસવાળો કે અસ્પષ્ટ ઉચ્ચાર; મધ્યમ tempo = આત્મવિશ્વાસપૂર્ણ અને સંયમિત બોલવાની રીત.u1  કોઈ અવાજની મેટાડેટા ઉપલબ્ધ ન હોવાથી, ટોનલ વિશ્લેષણ જવાબની લેખિત શૈલીના આધારે કરો (દા.ત. ઔપચારિક, અનૌપચારિક, દૃઢ, નમ્ર).u   ૩ ગુજરાતી શબ્દો અથવા નાના ગુજરાતી શબ્દસમૂહો જે જવાબનો એકંદર ભાવ દર્શાવે છે.	Malayalamu1   Malayalam (Malayalam script / മലയാളം)zml-INug  The question, ideal answer, and user's answer are all in Malayalam (Malayalam script). You MUST write ALL analysis fields — comparison, behavioralAnalysis, tonalAnalysis — entirely in Malayalam using Malayalam script. Do NOT mix English sentences inside the analysis fields. Technical terms may be kept in English only when no Malayalam equivalent exists.uS   ശബ്ദ ടോണൽ മെറ്റാഡാറ്റ (Voice Tonal Metadata):u.  സ്ഥിതിവിവരക്കണക്ക് വിശദീകരണം — കുറഞ്ഞ pitch_std = ഒരേ ഈണത്തിലുള്ള സംസാരം; കൂടിയ energy_fluctuation = വിറയ്ക്കുന്ന അല്ലെങ്കിൽ ഇടറുന്ന ശബ്ദം; കൂടിയ avg_flatness = വ്യക്തമല്ലാത്ത ഉച്ചാരണം; മിതമായ tempo = തികഞ്ഞ ആത്മവിശ്വാസത്തോടെയുള്ള സംസാരം.u  ശബ്ദ മെറ്റാഡാറ്റ ലഭ്യമല്ലാത്തതിനാൽ, ടോണൽ വിശകലനം എഴുതിയ ഉത്തരത്തിന്റെ ശൈലിയെ അടിസ്ഥാനമാക്കി ചെയ്യുക (ഉദാ: ഔദ്യോഗികം, സൗഹൃദപരം, ഉറച്ച, വിനയപൂർവ്വം).u  ഉത്തരത്തിന്റെ മൊത്തത്തിലുള്ള ഭാവം വ്യക്തമാക്കുന്ന 3 മലയാളം വാക്കുകൾ അല്ലെങ്കിൽ ചെറിയ വാക്യങ്ങൾ.Odiau$   Odia (Odia script / ଓଡ଼ିଆ)zor-INuN  The question, ideal answer, and user's answer are all in Odia (Odia script). You MUST write ALL analysis fields — comparison, behavioralAnalysis, tonalAnalysis — entirely in Odia using Odia script. Do NOT mix English sentences inside the analysis fields. Technical terms may be kept in English only when no Odia equivalent exists.uP   ସ୍ୱର ଟୋନାଲ୍ ମେଟାଡାଟା (Voice Tonal Metadata):u  ପରିସଂଖ୍ୟାନର ବ୍ୟାଖ୍ୟା — କମ୍ pitch_std = ଏକସ୍ୱର କଥାବାର୍ତ୍ତା; ଅଧିକ energy_fluctuation = ଥରୁଥିବା କିମ୍ବା କୁଣ୍ଠିତ ସ୍ୱର; ଅଧିକ avg_flatness = ଅସ୍ପଷ୍ଟ ଉଚ୍ଚାରଣ; ମଧ୍ୟମ tempo = ଆତ୍ମବିଶ୍ୱାସପୂର୍ଣ୍ଣ ଏବଂ ସଂଯମ କଥାବାର୍ତ୍ତା।u  ଯେହେତୁ କୌଣସି ସ୍ୱର ମେଟାଡାଟା ଉପଲବ୍ଧ ନାହିଁ, ଟୋନାଲ୍ ବିଶ୍ଳେଷଣ ଉତ୍ତରର ଲିଖିତ ଶୈଳୀ ଉପରେ ଆଧାର କରି କରନ୍ତୁ (ଉଦାହରଣ ସ୍ୱରୂପ: ଆନୁଷ୍ଠାନିକ, ଅନୌପଚାରିକ, ଦୃଢ଼, ନମ୍ର)।u   ୩ଟି ଓଡ଼ିଆ ଶବ୍ଦ କିମ୍ବା ଛୋଟ ଓଡ଼ିଆ ବାକ୍ୟାଂଶ ଯାହା ଉତ୍ତରର ସାମଗ୍ରିକ ଭାବ ପ୍ରକାଶ କରେ।)englishhindimarathitamiltelugukannadapunjabihinglishbengaligujarati	malayalamodiaLANGUAGE_CONFIGr   languagereturnc              	   C   sB   | pt   }|tvrtd| dt dt  d t }t| S )z
    Returns the language config dict for the given language key.
    Case-insensitive. Falls back gracefully to English with a warning log.
    zUnsupported language 'z'. Supported: z. Falling back to 'z'.)DEFAULT_LANGUAGEstriplowerr)   loggerwarningSUPPORTED_LANGUAGES)r*   key r3   E/var/www/eduai.edurigo.com/responseiq/testing/response_iq_analysis.pyget_language_config  s   r5   voice_inputc           	   
   C   sf  z| sW dS |  ds|  dretj| ddd}|  d}| dd	 }|d
d }d|v r9d|dd  }tjd|d}|jddD ]}|| qG|j	W  d   W S 1 s]w   Y  W dS d| v rp| dd } t
| }tjddd}|| |j	W  d   W S 1 sw   Y  W dS  ty } ztd|  W Y d}~dS d}~ww )z
    Accepts either a remote URL or a Base64-encoded audio string.
    Downloads / decodes it and saves to a temp file.
    Returns the temp file path, or empty string on failure.
     zhttp://zhttps://T<   )streamtimeoutz.mpeg?r   /.F)deletesuffix    )
chunk_sizeN,   z.wavzFailed to process audio input: )
startswithrequestsgetraise_for_statussplittempfileNamedTemporaryFileiter_contentwritenamebase64	b64decode	Exceptionr/   error)	r6   responser@   url_pathlast_segmenttmpchunk
audio_dataer3   r3   r4   download_or_save_audio  s8   (

(rZ   	file_pathc              
   C   s   z,|  ddd d }t| }|ddd}|j|dd td	|  |W S  t	yH } zt
d
|  | W  Y d}~S d}~ww )z
    Converts any audio file to WAV format (16-bit PCM, mono, 16kHz)
    required by speech_recognition. Uses pydub for format conversion.

    Returns the path to the converted WAV file.
    r>   rD   r   z_converted.wavi>     wav)formatzAudio converted to WAV: zAudio conversion failed: N)rsplitr   	from_fileset_channelsset_frame_rateset_sample_widthexportr/   inforQ   rR   )r[   wav_pathaudiorY   r3   r3   r4   _convert_to_wav  s   
rh   c                 C   s  d}z5zt |}|dd}td| d|   t| }tj|dd\}}tt|| }t	}t
|}	|j|	dd ||	}
W d   n1 sMw   Y  d	}z(|j|
|d
d}t|tru|di g}|rs|d dd	nd	}t| }W n- t
jy   td d	}Y n t
jy } ztd|  d	}W Y d}~nd}~ww |rt| nd}t|t|d d d}td| dt| d|dd|  ||t|d|dW W |r|| krzt| W S  ty   Y S w S S  ty8 } z4td|  d	dddt|dW  Y d}~W |r2|| kr3zt| W S  ty1   Y S w S S d}~ww |rS|| krTzt| W w  tyR   Y w w w w )u  
    Transcribes audio to text using Google Speech Recognition API
    via the speech_recognition library.

    Parameters
    ----------
    file_path : str
        Path to the audio file.
    language  : str, optional
        Language key (e.g. 'hindi', 'tamil'). Maps to Google's
        locale codes (hi-IN, ta-IN, etc.) for accurate recognition.

    Returns
    -------
    dict:
        'transcription'         – The transcribed text.
        'detected_language'     – Language locale used for recognition.
        'speaking_duration_sec' – Total audio duration in seconds.
        'words_per_minute'      – Estimated speaking rate.
    Nr   r	   z;Transcribing audio with Google Speech Recognition | locale=z | file=sr      ?)durationr7   F)r*   show_allalternativer   
transcriptz9Google Speech Recognition could not understand the audio.z%Google Speech Recognition API error: rD   r8   z Transcription complete | locale=z | text_length=z | duration=z.1fzs | wpm=r\   )transcriptiondetected_languagespeaking_duration_secwords_per_minutezSpeech transcription failed: unknown        )rp   rq   rr   rs   rR   )r5   rG   r/   re   rh   librosaloadfloatlen_recognizerrj   	AudioFileadjust_for_ambient_noiserecordrecognize_google
isinstancedictstrr-   UnknownValueErrorr0   RequestErrorrR   rI   roundmaxosremoverQ   )r[   r*   rf   lang_cfgr   ysr_ratetotal_duration
recognizersourcerX   transcription_textalternativesrY   
word_countrs   r3   r3   r4   transcribe_audio  s   

		r   c              
   C   s0  zt j| dd\}}t j||d\}}||t|k }t|dkr)tt|nd}t|dkr8tt|nd}t j	j
||d}t jj||d}	t|	dkrVt|	d nd}
t jj|dd }tt|}tt|}ttt jj||dd }ttt jj|dd }ttt jj|dd }g }|
dkr|d	 n|
d
k r|d n|d |dkr|d n	|dk r|d ||d  }|dkr|d n|d |dkr|d d||||
|||||ddW S  ty } ztd|  di dW  Y d}~S d}~ww )u   
    Extracts acoustic features using librosa.

    Returns
    -------
    dict:
        'summary' – Objective English description (LLM re-interprets in target language).
        'stats'   – Raw numeric features (language-agnostic).
    Nri   )r   rj   r   ru   )onset_enveloperj   )r      z,Fast speaking pace (high energy or nervous).P   z,Slow speaking pace (measured or low energy).zNormal/moderate speaking pace.r8   z6High pitch variation (expressive or excited delivery).   z3Low pitch variation (monotone or robotic delivery).gư>rk   zESignificant energy fluctuations (possible hesitation or shaky voice).z,Stable vocal energy (suggesting confidence).g?z(Breathy or noisy vocal texture detected. )avg_pitch_hz	pitch_std	tempo_bpm
avg_energyenergy_fluctuationavg_centroidavg_flatnessavg_zcr)summarystatszAudio analysis failed: z"Technical audio extraction failed.)rv   rw   piptracknpmedianry   rx   meanstdonsetonset_strengthbeattempofeaturermsspectral_centroidspectral_flatnesszero_crossing_rateappendjoinrQ   r/   rR   )r[   r   rj   pitches
magnitudespitches_masked	avg_pitchr   	onset_env	tempo_arr	avg_tempor   r   
energy_stdr   r   r   descenergy_ratiorY   r3   r3   r4   analyze_audio_features<  s^   




r   questionpredefined_answeruser_answeruser_voice_urlc                 C   s  t |}td|d  dt  d}d}|rFtd t|}|rFtd t||}td t|}zt| W n	 t	yE   Y nw d|d	  d
|d  d}	d}
|rsd|d  d|d  dt
j|d dd d|d  d	}
d}d}d}|r|dr|d }|}d| d|dd d|dd  d!|d"d  d#|d$d  d%|d&d  d'|d(d  d)}d*| d+| d,}|r|drd-|d$d  d.|d&d  d/|d  d0}nd1|d  d2|d3  }d}|rd4| d5}dg d6|d  d7|d	  d8|  d9| d:| d;| | |
 | d<|d  d=|r/d>nd d?|d  d@|r@dAnd dB|d  dC|d  dD|d  dE|r_dFnd dB|ridGnd dB|d  dH|d  dI| dB|d  dJ|dK  dL|d  dM|d  dN|d  dO}t||	ddPdQdRdSdTdU}d}ztdVt dW tjt|dXdY}|jdZkrd[t d\t }t| d]|iW S |  |
 }|d^d }d_|v r|d_d` dad   }nda|v r|dad` dad   }t
|}h db}||  }|rCtdc| dd |D ]}|dekr=g nd||< q4ztd tdft|dg |dg< W n ttfyc   d |dg< Y nw t|detsqg |de< t |de dhk r|de !d t |de dhk sz|de ddh |de< |r|dr|d |di< nd|di< tdj|dg  dk|d  dl|dirdmndn  |W S  t
j"y   tdo dp|dq Y S  tj#y } ztdr|  d]dst$| iW  Y d}~S d}~ww )tu  
    Evaluates a candidate's answer against the ideal answer using qwen2.5:14b.

    Parameters
    ----------
    question           : The interview / assessment question.
    predefined_answer  : The ideal / expected answer.
    user_answer        : The candidate's actual answer.
    user_voice_url     : Optional URL or Base64 audio of the candidate's answer.
    language           : Language key — one of: english, hindi, marathi, tamil,
                         telugu, kannada, punjabi.  Defaults to 'english'.

    Returns
    -------
    dict with keys: matchScore, comparison, behavioralAnalysis, tonalAnalysis,
                    visuals, voiceTranscription (when voice provided)
    zStarting analysis | language=r
   z	 | model=NzProcessing audio input...z!Transcribing audio via Whisper...z+Extracting acoustic features via librosa...znYou are a world-class communication expert, behavioral psychologist, and tonal analyst with deep expertise in r   z. Your goal is to provide a deep, professional evaluation of a candidate's interview response. Analyze the text for semantic accuracy AND the voice for emotional nuance when voice data is provided. r   uf    Return the result ONLY in strict JSON format — no markdown code fences, no preamble, no extra text.r7   z
    r   z+
    Objective Delivery Summary (English): r   z
    Raw Acoustic Stats: r   F)ensure_asciiz
    (r   z)
    rp   u  
    ═══════════════════════════════════════════════════════════════
    VOICE TRANSCRIPTION (What the candidate actually SPOKE):
    ═══════════════════════════════════════════════════════════════
    Transcribed Text    : "z"
    Detected Language   : rq   rt   z
    Confidence Score    : 
confidencer   z
    Speaking Duration   : rr   z# seconds
    Words Per Minute    : rs   z
    Pause Count         : pause_countz+ (pauses > 1.5s)
    Total Pause Duration: total_pause_duration_secz seconds
    u  
    ═══════════════════════════════════════════════════════════════
    SPEECH-TEXT CONSISTENCY CHECK:
    ═══════════════════════════════════════════════════════════════
    The user typed this answer  : "z%"
    The user SPOKE this answer  : "u  "

    IMPORTANT: Compare the typed answer with the spoken answer above.
    If they differ significantly, this is a CRITICAL observation —
    the candidate may have typed one thing but said something different.
    Factor this into ALL analysis fields (comparison, behavioralAnalysis,
    tonalAnalysis). The SPOKEN answer should be treated as the PRIMARY
    source of truth for what the candidate actually communicated.
    uE  You have ACTUAL VOICE DATA with both transcription and acoustic metrics. Provide a comprehensive tonal analysis that includes: (a) Vocal delivery assessment — confidence, pace, fluency, emotional tone based on the acoustic stats (pitch variation, energy, tempo). (b) Speech clarity — articulation quality, speaking rate (z WPM), pauses (u    detected). (c) Emotional indicators — nervousness, confidence, hesitation based on energy fluctuations and pause patterns. (d) Speech-text alignment — note if spoken words differ from typed answer. Write the ENTIRE analysis in r>   zIf voice metadata IS provided above: give a detailed breakdown of the delivery (confidence, pace, emotional stability) written in z. r   zg
    NOTE: The candidate provided BOTH a typed answer and a voice answer. The voice transcription is: "z". Use the SPOKEN answer as the PRIMARY basis for matchScore calculation, since it represents what the candidate actually communicated verbally. The typed answer should be used as supplementary context.zc
Evaluate the following interview response with high precision.

INPUT DATA:
- Content Language  : z (z)
- Question          : "z"
- Ideal Answer      : "z"
- User's Typed Answer : "z"
u;   

REQUIRED ANALYSIS — ALL text fields MUST be written in u|   :

1. matchScore (integer 0–100):
   Quantify how well the user's answer covers the core concepts of the ideal answer.
   zRWhen voice transcription is available, score primarily based on the SPOKEN answer.z
   Be strict but fair. Deduct points for missing key ideas; award partial credit for partial coverage.

2. comparison (text in u   ):
   A professional 2–3 sentence summary explaining WHY the score was given.
   Highlight what was covered correctly and what key points were missing.
   ztIf the spoken answer differs from the typed answer, explicitly mention this discrepancy and its impact on the score.z
   z!

3. behavioralAnalysis (text in z):
   Analyse the candidate's communication style:
   - Are they assertive, analytical, empathetic, or vague?
   - Is there logical flow and a coherent structure?
   - Comment on vocabulary richness and appropriateness for z.
   zl- Analyse speech-text consistency: did the candidate say what they typed, or were there notable differences?zF- Comment on verbal fluency: hesitations, filler words, speaking pace.z

4. tonalAnalysis (text in z):
   z,

5. visuals (array of exactly 3 items):
   r   u   

OUTPUT FORMAT — strict JSON only, absolutely no markdown fences or extra text:
{
    "matchScore": <integer 0-100>,
    "comparison": "<text in z(>",
    "behavioralAnalysis": "<text in z#>",
    "tonalAnalysis": "<text in z1>",
    "visuals": ["<kw1>", "<kw2>", "<kw3>"]
}
jsong333333?rA   i   )temperaturenum_ctxnum_predict)modelpromptsystemr9   r^   optionsu   Calling Ollama API — model: ...i,  )r   r:   i  zModel 'z?' not found on this Ollama instance. Pull it with: ollama pull rR   rS   z```jsonrD   z```>   visuals
comparison
matchScoretonalAnalysisbehavioralAnalysiszLLM response is missing keys: z. Filling with defaults.r   d   r      voiceTranscriptionzAnalysis complete | matchScore=z | language=z | has_transcription=yesnoz'Failed to parse JSON from LLM response.zLLM returned invalid JSON.)rR   raw_responsezOllama connection error: zCould not connect to Ollama: )%r5   r/   re   OLLAMA_MODELrZ   r   r   r   r   rQ   r   dumpsrG   r   rF   postOLLAMA_API_URLstatus_coderR   rH   r-   rI   loadskeysr0   r   minint
ValueError	TypeErrorr   listry   r   JSONDecodeErrorRequestExceptionr   )r   r   r   r   r*   r   audio_featuresvoice_transcriptionaudio_file_pathsystem_promptaudio_context_blockvoice_transcription_blockspeech_consistency_blocktranscribed_textvttonal_instructionanswer_source_noter   payloadllm_response_textrS   msgresultparsedrequired_keysmissingkrY   r3   r3   r4   analyze_response  s  









	



	

 !"%*+,5




 

r   __main__u!   Response IQ — CLI Analysis Tool)descriptionformatter_classz
--questionzThe interview question)typehelpz--predefinedzThe ideal answerz--userzThe user's answerz--voicez0URL or Base64-encoded audio of the user's answer)r   defaultr   z
--languagez$Language of the content. Supported: )r   r   choicesr   z--json_inputztPath to a JSON file OR a raw JSON string.
Expected keys: question, predefinedAnswer, userAnswer, userVoice, languagezutf-8)encodingpredefinedAnswer
userAnswer	userVoicezError parsing --json_input: rD   u,   No input provided — running Hindi demo...
u*   एडुरिगो क्या है?u  एडुरिगो एक व्यापक लर्निंग और एंगेजमेंट प्लेटफ़ॉर्म है, जिसे संगठनों के लिए ट्रेनिंग, असेसमेंट, गेमिफिकेशन और एनालिटिक्स प्रदान करने के लिए डिज़ाइन किया गया है। यह व्यवसायों को कर्मचारियों, पार्टनर्स और ग्राहकों को इंटरैक्टिव और स्केलेबल लर्निंग सॉल्यूशन्स के माध्यम से अपस्किल करने में मदद करता है।u  एडुरिगो एक व्यापक लर्निंग और एंगेजमेंट प्लेटफ़ॉर्म है, जिसे संगठनों के लिए ट्रेनिंग, असेसमेंट, गेमिफिकेशन और एनालिटिक्स प्रदान करने के लिए डिज़ाइन किया गया है।r   u   ─────────────────────────────────────────────────────────────────z  Model       : z  Language    : z  Question    : z  User Answer : r   r   r7   z  Voice       : r8   )r*   u   
── Analysis Result ──────────────────────────────────────────
r\   F)indentr   )N)NN)Jr   rF   r   loggingrJ   rv   numpyr   rO   speech_recognitionrj   pydubr   typingr   r   r   basicConfigINFO	getLoggerr/   r   r   
Recognizerrz   r)   r   __annotations__r,   r   r   r1   r5   rZ   rh   r   r   r   __name__argparsesysArgumentParserRawTextHelpFormatterparseradd_argument
parse_argsargsr   
predefineduservoicer*   qpauauvlang
json_inputsrcpathisfileopenfrw   datar   rG   rQ   rY   printexitry   r   r   r3   r3   r3   r4   <module>   s  
 
    X*$fU

  
/
	




,