o
    Mnh                    @   s   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 d dlZd dlZd dlmZ eeZe
G dd dZG d	d
 d
ZdS )    N)ListDictAnyOptional)defaultdict)	dataclass)SequenceMatcher)Ollamac                   @   sJ   e Zd ZU eed< eed< eed< eed< eeeef  ed< eed< dS )CourseRecommendation	course_idnameshort_descriptiondescriptionskillsrelevance_scoreN)	__name__
__module____qualname__str__annotations__r   r   r   float r   r   P/var/www/eduai.edurigo.com/doc_train/edurigo_ai/TNA/testing/training_analysis.pyr
      s   
 r
   c                   @   sh  e Zd ZdZdd Zdeeee f fddZdeeee f fddZ	deeee f fd	d
Z
dedee dee dee dee deeeef  fddZdedefddZdededee dee dee defddZdededefddZdededefddZdededefddZdedee fd d!Zd"ededefd#d$Zdededefd%d&Zdedee defd'd(Zdededefd)d*Zdedee defd+d,Zdededee defd-d.Zdedee fd/d0Zd1eeeef  dedeeeef  fd2d3Zded4edee dee dee dee defd5d6Zdedededefd7d8Zdedee dedefd9d:Z dedee dedefd;d<Z!dededee defd=d>Z"ded4edee dee d?eeeef  defd@dAZ#dBedefdCdDZ$ded4edee dee def
dEdFZ%dededee dee dGedefdHdIZ&dJedKedLee defdMdNZ'dOee dee dLee defdPdQZ(dRedSedLee defdTdUZ)dJedRededKedef
dVdWZ*dSedLee dXedefdYdZZ+dJedSedKedefd[d\Z,dJedLee defd]d^Z-d_ed`ee daee dJededXedefdbdcZ.dedefdddeZ/dfS )gTrainingAnalyzerz\
    Professional Training Analysis helper class for intelligent course recommendations
    c                 C   s.   |   | _|  | _|  | _tdd| _d S )Nz
gemma3:12b)model)_load_skill_keywordsskill_keywords_load_department_keywordsdepartment_keywords_load_industry_synonymsindustry_synonymsr	   llmselfr   r   r   __init__   s   


zTrainingAnalyzer.__init__returnc              	   C   6   g dg dg dg dg dg dg dg dd	S )
zQ
        Load comprehensive skill-related keywords for enhanced matching
        ))programmingcodingdevelopmentsoftwaretechitcomputerdigitalcybernetworkdatabasecloudwebmobileapi	framework	algorithmdata	analyticsmachine learningaizartificial intelligencepythonjava
javascriptreactangulardevops
kubernetesdockerawsazuremicroservicessecurity
blockchainiot
automationtestingqaagilescrum)
management
leadershipteamprojectstrategyplanningcoordinationsupervisionadministration
governance	oversightdirectormanagerlead	executivestakeholderzdecision making
delegation	mentoringcoachingzperformance management	budgetingzresource allocationzchange managementzorganizational development)communicationpresentationwritingspeakingnegotiationcollaborationinterpersonalzcustomer servicezpublic speakingfacilitation	mediationzconflict resolutionzactive listeningfeedbackstorytelling
persuasion	influence
networkingzcultural competencyzemotional intelligencezcross-cultural)businessfinance
accounting	marketingsales
operationshrhuman resourcesrS   analysis
consulting	economicsentrepreneurship
innovationtransformationzprocess improvementbusiness intelligencezmarket researchzcompetitive analysisroikpimetricsforecastingzrisk management
compliance)designcreativeartisticvisualgraphics
multimediacontentmediaphotographyvideo	animationuxuibrandingillustration
typographyzcolor theorywireframingprototypingzuser research	usabilityaccessibilityadobefigmasketch	photoshopillustratorzafter effects)qualityrK   rL   r   	standardsauditreview
inspection
validationverificationiso	six sigmaleancontinuous improvementzprocess optimizationdocumentationzbest practicesmethodologyr6   rX   control)r8   r9   
statistics	reportingvisualization	dashboardbir   sqlexceltableauzpower bir<   rr:   data sciencezbig dataetlzdata warehousezdata miningzpredictive modelingzstatistical analysis)rP   teamworkzproblem solvingzcritical thinking
creativityadaptabilityflexibility
resilienceztime managementorganizationprioritizationmultitaskingzstress managementzwork-life balanceproductivity
efficiencyzattention to detailreliability)	technicalrO   rc   rq   r   r   r8   soft_skillsr   r"   r   r   r   r   "   s   z%TrainingAnalyzer._load_skill_keywordsc              	   C   r&   )
zO
        Load department-specific keywords for better context matching
        )
technologyr*   r'   r0   r1   r/   r.   r+   r-   systemr3   r4   r2   r8   infrastructurerG   r)   )r'   r(   r)   r*   r3   r4   frontendbackend	fullstackr5   r6   r1   r>   r<   r=   r?   r@   )rx   recruitmenthiringemployeerO   rP   rc   trainingr)   performancetalent
onboardingcompensationbenefits)rs   	financialbudgetcost
investmentry   r   r   r   r{   taxationpayrollr   risktreasury)processworkflowr   optimizationrO   	logisticszsupply chainr   improvementr   r   rJ   r   )rt   advertising	promotioncampaignbrandzdigital marketingzsocial mediar   customerseosemzemail marketingr9   )ru   sellingrg   r   clientrevenuetargetcrmzlead generationzaccount managementprospectingclosingpipeline)productr)   r   zuser experiencezuser interfacerequirementsspecificationroadmapfeaturerM   rN   	prototyperK   r,   	developerrw   rr   rv   rt   ru   r   r   r"   r   r   r   r   _   s   z*TrainingAnalyzer._load_department_keywordsc                 C   s0   g dg dg dg dg dg dg ddS )	zN
        Load industry-specific synonyms for better semantic matching
        )r'   r(   buildingcreatingengineeringimplementation)rP   rW   rX   rV   rU   )r9   examination
evaluation
assessmentresearchinvestigation)interactiondialogueconversationcorrespondence
engagement)	educationlearningr)   instructionra   r`   )enhancementr   
bettermentadvancementupgrade)rT   approachr   r6   r   vision)r)   rO   ry   rc   r   r   rS   r   r"   r   r   r   r   n   s   z(TrainingAnalyzer._load_industry_synonyms
user_queryfiltered_skillsdepartment_nameall_skills_dataall_coursesc                 C   s  zt d|  t dt|  t d|rt|nd  g }| |}|D ]Y}z4| |||||}	|	dkr_| |||||	}
|j|j|j|j	dd |j
D t|	d|
d	}|| W q* ty } zt d
t|dd dt|  W Y d}~q*d}~ww |jdd dd | ||}|dd }t dt| d |W S  ty } zt dt|  g W  Y d}~S d}~ww )zp
        Recommend courses based on user query, skills, and department using advanced scoring algorithm
        z*Starting course recommendation for query: zAvailable courses: zFiltered skills: r   皙?c                 S   s   g | ]}|  qS r   )dict.0skillr   r   r   
<listcomp>       z6TrainingAnalyzer.recommend_courses.<locals>.<listcomp>   )courseIdr   r   r   r   r   reasonzError processing course r  unknownz: Nc                 S   s   | d S )Nr   r   )xr   r   r   <lambda>   s    z4TrainingAnalyzer.recommend_courses.<locals>.<lambda>T)keyreverse	   z
Returning z course recommendationszError in recommend_courses: )loggerinfolen_preprocess_text_calculate_course_relevance_generate_recommendation_reasonr  r   r   r   r   roundappend	Exceptionwarninggetattrr   sort_apply_diversity_filtererror)r#   r  r  r  r  r  course_scoresprocessed_querycoursescorer  course_recommendationcourse_errordiverse_coursesfinal_recommendationser   r   r   recommend_courses|   sP   	



	"z"TrainingAnalyzer.recommend_coursestextc                 C   s8   |sdS |  }tdd|}tdd|}| }|S )z5
        Preprocess text for better matching
         [^\w\s] z\s+)lowerresubstrip)r#   r;  r   r   r   r&     s   z!TrainingAnalyzer._preprocess_textr3  c              
   C   s   zSd}|  ||}||d 7 }|dkr>|r"| |||}||d 7 }|r1| |||}	||	d 7 }| |||}
||
d 7 }| |||}||7 }tt|dd}|W S  typ } zt	dt
|  W Y d}~dS d}~ww )	z_
        Calculate comprehensive relevance score with VERY HIGH priority to user_query
                ffffff?r  333333?皙?      ?z$Error calculating course relevance: N)_calculate_query_relevance%_calculate_department_query_relevance*_calculate_filtered_skills_query_relevance%_calculate_all_skills_query_relevance_calculate_query_bonus_scoreminmaxr+  r#  r0  r   )r#   r3  r  r  r  r  total_scorequery_scoredept_query_scorefiltered_skills_query_scoreall_skills_query_scorebonus_scorenormalized_scorer9  r   r   r   r'     s,   	z,TrainingAnalyzer._calculate_course_relevancec              
   C   s0  zz|sW dS |  }|j d|j d|j   }ttd|}ttd|}h d}|| }|| }||}|rDt|t| nd}	| 	||}
| 
||}| |j  |}| ||}|	d |
d  |d  |d  |d  }t|dW S  ty } ztd	t|  W Y d
}~dS d
}~ww )z`
        Calculate how well the course matches the user query using multiple techniques
        rC  r>  \b\w+\b>'   aanatbebydoinisofonortoandarebutcandidforhadhasmaythewasbeendoeshavemustthatthiswerewillwithbeingcouldmightthesethosewouldshouldg      ?g?r  rG  z#Error calculating query relevance: N)r?  r   r   r   setr@  findallintersectionr%  _calculate_semantic_similarity_calculate_phrase_matching_calculate_title_relevance_calculate_synonym_matchingrM  r+  r#  r0  r   )r#   r3  r  query_lowercourse_textquery_wordscourse_words
stop_wordscommon_wordsword_overlap_scoresemantic_scorephrase_scoretitle_scoresynonym_scorefinal_scorer9  r   r   r   rH     s@   
z+TrainingAnalyzer._calculate_query_relevancequeryr  c           
   
   C   s   zIt  }t  }| j D ]\}}|D ]}||v r|| qq| j D ]\}}|D ]}||v r5|| q*q$|rGt||}|t| W S W dS  tyf }	 ztdt	|	  W Y d}	~	dS d}	~	ww )zH
        Calculate semantic similarity using keyword categories
        rC  z'Error calculating semantic similarity: N)
r~  r   itemsaddr%  r  r+  r#  r0  r   )
r#   r  r  query_categoriescourse_categoriescategorykeywordskeywordoverlapr9  r   r   r   r  3  s0   

z/TrainingAnalyzer._calculate_semantic_similarityc           	   
   C   s   z2|  |}|  |}|sW dS d}|D ]}|D ]}td|| dkr*|d7 } nqq|t| W S  tyO } ztdt|  W Y d}~dS d}~ww )z1
        Calculate phrase-level matching
        rC  r   N皙?   z#Error calculating phrase matching: )_extract_phrasesr   ratior%  r+  r#  r0  r   )	r#   r  r  query_phrasescourse_phrasesmatchesquery_phrasecourse_phraser9  r   r   r   r  R  s&   

z+TrainingAnalyzer._calculate_phrase_matchingc              
   C   s   t d|}g }tt|d D ]}|||  d||d    qtt|d D ]}|||  d||d   d||d    q+|S )z6
        Extract meaningful phrases from text
        rV  r  r>     )r@  r  ranger%  r*  )r#   r;  wordsphrasesir   r   r   r  k  s   "0z!TrainingAnalyzer._extract_phrasescourse_titlec              
   C   s   z6||v rW dS t td|}t td|}h d}|| }|| }|s)W dS t||}|t| W S  tyS } ztdt|  W Y d}~dS d}~ww )z;
        Calculate relevance based on course title
        rG  rV  >   rW  rX  rY  r[  r]  r_  r`  ra  rb  rc  re  rh  rl  rv  rC  z#Error calculating title relevance: N)	r~  r@  r  r%  r  r+  r#  r0  r   )r#   r  r  title_wordsr  r  r  r9  r   r   r   r  |  s"   z+TrainingAnalyzer._calculate_title_relevancec           	   
   C   s   z1d}d}| j  D ]\}}||v r%|t|7 }|D ]
}||v r$|d7 }qq
|dkr/|| W S dW S  tyN } ztdt|  W Y d}~dS d}~ww )z6
        Calculate matching based on synonyms
        r   r  rC  z$Error calculating synonym matching: N)r    r  r%  r+  r#  r0  r   )	r#   r  r  r  total_synonyms	base_wordsynonymssynonymr9  r   r   r   r    s    z,TrainingAnalyzer._calculate_synonym_matchingc              
   C   sH  z|sW dS dd |D }|j  d|j d|j  }dd |jD }d}dt| }|D ]R}d}	||v r9d}	n+||v r@d}	n$|D ]!}
td||
 }|d	krXt|	|d	 }	qB|d
krct|	|d
 }	qB|	dkrz|	 }|D ]}||v ryt|	d}	qn||	| 7 }q.t
|dW S  ty } ztdt|  W Y d}~dS d}~ww )zU
        Calculate relevance based on filtered skills with enhanced matching
        rC  c                 S      g | ]}|j  qS r   
skill_namer?  r  r   r   r   r        zITrainingAnalyzer._calculate_filtered_skills_relevance.<locals>.<listcomp>r>  c                 S   r  r   r  r  r   r   r   r    r  rG  ?Nr  333333?g333333?z-Error calculating filtered skills relevance: )r   r   r   r?  r   r%  r   r  rN  splitrM  r+  r#  r0  r   )r#   r3  r  skill_namesr  course_skill_namesrO  weight_per_skillr  skill_scorecourse_skill
similarityskill_wordswordr9  r   r   r   $_calculate_filtered_skills_relevance  sD   
z5TrainingAnalyzer._calculate_filtered_skills_relevancec           
   
   C   s  zd|sW dS |  }|j d|j d|j   }||v r W dS | |}|s*W dS d}|D ]}||v r<|dt| 7 }q.|dkr_|D ]}| D ]}td|| dkr]|dt| 7 }qIqCt	|dW S  t
y }	 ztdt|	  W Y d}	~	dS d}	~	ww )zP
        Calculate relevance based on department with enhanced matching
        rC  r>  rG  NrD  g      ?z(Error calculating department relevance: )r?  r   r   r   _get_department_keywordsr%  r  r   r  rM  r+  r#  r0  r   )
r#   r3  r  
dept_lowerr  dept_keywordsmatch_scorer  course_wordr9  r   r   r   _calculate_department_relevance  s8   
z0TrainingAnalyzer._calculate_department_relevancec              
      s  zk|sW dS |j  d|j d|j  }dd |jD }g }|D ]}|j   |v s0 |v r5|| q!|rid}|D ]"}|j  | j D ]\}}	t	 fdd|	D r]|d7 } nqHq<t
|t| d	W S W dS  ty }
 ztd
t|
  W Y d}
~
dS d}
~
ww )zV
        Calculate relevance based on all available skills (fallback scoring)
        rC  r>  c                 S   r  r   r  r  r   r   r   r    r  zDTrainingAnalyzer._calculate_all_skills_relevance.<locals>.<listcomp>r   c                 3       | ]}| v V  qd S Nr   r  r  r  r   r   	<genexpr>      zCTrainingAnalyzer._calculate_all_skills_relevance.<locals>.<genexpr>r  rG  z(Error calculating all skills relevance: N)r   r   r   r?  r   r  r*  r   r  anyrM  r%  r+  r#  r0  r   )r#   r3  r  r  r  relevant_skillsr  category_matchesr  r  r9  r   r  r   _calculate_all_skills_relevance  s8   


z0TrainingAnalyzer._calculate_all_skills_relevancec              
   C   s   z]d}|j  d|j d|j  }| }||j  v r!|d7 }|rBd}|D ]}|j |v r4|d7 }q'|dkrB|t|d d7 }g d}	|	D ]}
|
|v rZ|
|v rZ|d7 } |W S qH|W S  tyz } ztd	t	|  W Y d
}~dS d
}~ww )zS
        Calculate bonus score for exact matches and high-value indicators
        rC  r>  r  r   r  g{Gz?)advancedexpertprofessionalcertificationcomprehensivemasterclassrF  zError calculating bonus score: N)
r   r   r   r?  r  rM  r+  r#  r0  r   )r#   r3  r  r  bonusr  r  skill_matchesr  high_value_keywordsr  r9  r   r   r   _calculate_bonus_score+  s6    z'TrainingAnalyzer._calculate_bonus_scorec              
   C   s   zN|| j v r| j | W S | j  D ]\}}||v s||v r"|  W S qd}d}| j  D ]\}}td|| }||krD|dkrD|}|}q,|rJ|W S g dW S  tyn } ztdt|  g dW  Y d}~S d}~ww )zN
        Get relevant keywords for a department with enhanced mapping
        NrC  r  )rO   r  r  r   r)   rP   z#Error getting department keywords: )r  r   r)   )r   r  r   r  r+  r#  r0  r   )r#   r  dept_keyr  
best_match
best_ratior  r9  r   r   r   r  P  s.   


z)TrainingAnalyzer._get_department_keywordsr1  c           	   
   C   s  zct |dkr
|W S g }t }|D ]+}ttd|d  }|r*t ||dk r<|| || t |dkr< nqdt | }|dkra|D ]}||vr`|| |d8 }|dkr` |W S qI|W S  ty } zt	
dt|  |d	d W  Y d	}~S d	}~ww )
zM
        Apply diversity filter to ensure variety in recommendations
        r"  rV  r   r     r   r  z!Error applying diversity filter: N)r%  r~  r@  r  r?  r  r*  updater+  r#  r0  r   )	r#   r1  r  r7  used_keywordsr3  course_keywordsremaining_slotsr9  r   r   r   r/  r  s:   


 z(TrainingAnalyzer._apply_diversity_filter
admin_namec           
   
      s   z| j |||||d}| j|||||dI dH }||fW S  tyA }	 ztdt|	  g d| dfW  Y d}	~	S d}	~	ww )zG
        Get course recommendations and generate response text
        )r  r  r  r  r  )r  r  r  r  recommended_coursesNz+Error in get_recommendations_and_response: zBased on your goal to z5, we have identified relevant training opportunities.)r:   _generate_enhanced_response_textr+  r#  r0  r   )
r#   r  r  r  r  r  r  r  response_textr9  r   r   r    get_recommendations_and_response  s,   
	
z1TrainingAnalyzer.get_recommendations_and_responsec              
   C   x   z|  ||}| ||}|dkr|dkr|| d W S W dS  ty; } ztdt|  W Y d}~dS d}~ww )zQ
        Calculate relevance based on department AND user query combined
        r  r  rC  z.Error calculating department query relevance: N)r  rH  r+  r#  r0  r   )r#   r3  r  r  
dept_scorerP  r9  r   r   r   rI       z6TrainingAnalyzer._calculate_department_query_relevancec              
   C   r  )zV
        Calculate relevance based on filtered skills AND user query combined
        r  r  rC  z3Error calculating filtered skills query relevance: N)r  rH  r+  r#  r0  r   )r#   r3  r  r  skills_scorerP  r9  r   r   r   rJ    r  z;TrainingAnalyzer._calculate_filtered_skills_query_relevancec              
   C   r  )zQ
        Calculate relevance based on all skills AND user query combined
        r  r  rC  z.Error calculating all skills query relevance: N)r  rH  r+  r#  r0  r   )r#   r3  r  r  r  rP  r9  r   r   r   rK    r  z6TrainingAnalyzer._calculate_all_skills_query_relevancec              
   C   sT  zd}|j  d|j d|j  }| }||j  v r"|d7 }n||j v r-|d7 }ttd|}ttd|}h d}	||	 }|rct||t| }
|
dkr[|d7 }n|
d	krc|d
7 }|rd}|D ]}|j	 }||v r|||v r||d7 }qi|dkr|t
|d d7 }|W S  ty } ztdt|  W Y d}~dS d}~ww )zE
        Calculate bonus score for exceptional query matches
        rC  r>  rE  r  rV  >   rW  rX  rY  r[  r]  r_  r`  ra  rb  rc  re  rh  rl  rv  r  g{Gz?r  rF  r   r  gQ?z%Error calculating query bonus score: N)r   r   r   r?  r~  r@  r  r%  r  r  rM  r+  r#  r0  r   )r#   r3  r  r  r  r  r  r  r  r  overlap_ratioskill_query_alignmentr  r  r9  r   r   r   rL    sB   


z-TrainingAnalyzer._calculate_query_bonus_scorer  c              
      s$  zlg }|r| d|  |r| d|  |r0dd |dd D }| dd|  |rHd	d |dd
 D }| dd|  d|}	d|	 d}
| j|
I dH }| |}|rkd| d| }|W S  ty } ztdt|  | 	||||W  Y d}~S d}~ww )zi
        Generate highly advanced, comprehensive response text using LLM with formatting markers
        zTraining objective: zDepartment: c                 S      g | ]}|j qS r   r  r  r   r   r   r  =      zETrainingAnalyzer._generate_enhanced_response_text.<locals>.<listcomp>N   zTarget skills: , c                 S   s   g | ]}|d  qS )r   r   )r  r3  r   r   r   r  B  r     zTop recommended training: 
a  
    You are a senior training and development consultant providing strategic guidance. Based on the following analysis, create a comprehensive, professional response that demonstrates deep understanding of learning and development principles.

    CONTEXT:
    a  

    REQUIREMENTS:
    - Write in a sophisticated, consultative tone
    - Focus on strategic training insights and learning pathways
    - Provide actionable recommendations for skill development
    - Include industry best practices and learning methodologies
    - Address competency gaps and development opportunities
    - Emphasize measurable outcomes and performance improvement
    - DO NOT mention any specific courses, online platforms, or training providers
    - DO NOT include course listings or external learning resources
    - Keep response between 200-300 words
    - Structure with clear, logical flow
    - Use **text** for important key points and terms
    - Use ##Section Title## for main sections if needed
    - Use *emphasis* for subtle highlights
    - Use bullet points with - for lists when appropriate

    Create a response that positions you as a trusted learning and development advisor providing strategic guidance for professional growth and organizational capability building.
    z**Dear z,**

z$Error generating enhanced response: )
r*  joinr!   ainvoke_clean_and_format_llm_responser+  r#  r0  r   _generate_fallback_response)r#   r  r  r  r  r  context_partsr  top_coursescontext_strpromptresponsecleaned_responser9  r   r   r   r  &  s6   	

z1TrainingAnalyzer._generate_enhanced_response_textr  c              
      s|  zd | }g d}|D ]}tj|d|tjd}qg d}|D ]}dt| d }tj|d| d|tjd}q"g d}|D ]"\}}	| | v rdtjd	t| d
|	 d|tjd} nqBg d}
|
D ]}dt| d }tj|d| d|tjd}qkg d}|D ]&}t||}|D ]}|d}d|d d|d }|	||}qq|d}g }g }t
|D ]N\}     r|t|d k rۈ dsۈ d7  |  t|dkrt fdddD r|d | g }qt|dkr|d | g }q|r|d | d |W S  ty= } ztdt|  |W  Y d}~S d}~ww )zP
        Clean and format LLM response with enhanced formatting markers
        r>  )zM\b(?:course|training|program|certification|workshop|seminar|class|module)s?\bzX\b(?:online|offline|digital|virtual|in-person|classroom)\s+(?:course|training|program)\bzB\b(?:udemy|coursera|linkedin|youtube|edx|pluralsight|skillshare)\bzlearning opportunity)flags)zcompetency developmentzskill enhancementzperformance improvementzstrategic learningzprofessional developmentzcapability buildingzmeasurable outcomeszcareer progressionzorganizational excellencezindustry best practiceszlearning pathwaysztalent optimizationzknowledge transferr   zworkforce developmentzstrategic alignmentzbusiness impactROIzproductivity gainsz\b**))zBased onz##Strategic Analysis##)zOur analysisz##Assessment Results##)zWe recommendz##Key Recommendations##)zThe approachz##Implementation Strategy##)z	This willz##Expected Outcomes##()z

\1)	zcritical success factorszimmediate impactzlong-term benefitszcompetitive advantagezorganizational transformationz
skill gapszlearning objectiveszperformance metricszdevelopment priorities*)z(\d+\.)\s*([A-Z][^.]*\.)z?(First|Second|Third|Finally|Additionally|Moreover),\s*([^.]*\.)zC(Key areas include|Focus areas are|Priorities include):\s*([^.]*\.)r   z- **r  z** r  z. .c                 3   r  r  r   )r  markersentencer   r   r    r  zBTrainingAnalyzer._clean_and_format_llm_response.<locals>.<genexpr>)z##r  r   r  

z,Error cleaning and formatting LLM response: N)r  r  r@  rA  
IGNORECASEescaper?  finditergroupreplace	enumeraterB  r%  endswithr*  r  r+  r#  r0  r   )r#   r  cleanedcourse_patternspattern	key_termstermsection_indicators	indicatorheaderemphasis_phrasesphrasebullet_patternsr  matchoriginal	formatted
paragraphsformatted_paragraphscurrent_paragraphr  r9  r   r  r   r  q  sf   
(


"z/TrainingAnalyzer._clean_and_format_llm_responsec           
   
   C   s   z^g }|r| d| d |r| d| d n| d |r1| |}| d| d|  |rJdd	 |d
d D }| dd| d | d | d | d d|W S  ty{ } ztdt|  W Y d
}~dS d
}~ww )z9
        Generate fallback response if LLM fails
        zDear ,zBased on your objective to z[, we have conducted a comprehensive analysis of your training and development requirements.zTWe have conducted a thorough analysis of your training and development requirements.zFor the z department, c                 S   r  r   r  r  r   r   r   r    r  z@TrainingAnalyzer._generate_fallback_response.<locals>.<listcomp>Nr  z;The analysis reveals critical development opportunities in r  zN, which are essential for professional advancement and organizational success.zOur recommendation emphasizes a structured approach to capability building that aligns with industry best practices and focuses on measurable competency development.zThe strategic learning pathway we've identified will enhance performance outcomes, support career progression, and contribute to organizational excellence through targeted skill enhancement and professional development initiatives.zThis comprehensive approach ensures sustainable learning outcomes and measurable impact on both individual and organizational performance.r  z$Error generating fallback response: zWe have identified relevant training opportunities based on your requirements and conducted a comprehensive analysis to support your professional development objectives.)
r*  _get_department_insightsr  r+  r#  r0  r   r   r   r   )
r#   r  r  r  r  response_partsdept_insightsr  r9  r  r   r   r   r    s,   




z,TrainingAnalyzer._generate_fallback_responser4  c              
   C   s  zg }|r/|  }|j d|j   }ttd|}	|	D ]}
|
|v r.|d|   nq|rsg }|D ]}|j  }||j d|j   v rO||j q5|rst|dkrd|d|d  d n|dd		|d
d   |r| 
|  }|j d|j   }|D ]}||v r|d| d  nq|dkr|d n	|dkr|d |rdd	|d
d  dW S W dS  ty } ztdt|  W Y d
}~dS d
}~ww )zG
        Generate intelligent reason for course recommendation
        r>  rV  z directly addresses your goal of r  z	develops r   z competencyz#enhances multiple skills including r  Nr  zaligns with z department requirementsr  z)shows exceptional relevance to your needsr  z2demonstrates strong alignment with your objectiveszRecommended because it  and r  zJRecommended based on comprehensive analysis of your training requirements.z(Error generating recommendation reason: z(Recommended based on relevance analysis.)r?  r   r   r~  r@  r  r*  r  r%  r  r  r+  r#  r0  r   )r#   r3  r  r  r  r4  reasonsr  r  r  r  r  r  r  r  r  r9  r   r   r   r(  )  sT   

z0TrainingAnalyzer._generate_recommendation_reasoncourse_namer  r  c           
   
   C   s   zQ||v rd| dW S t td|}t |}||}t|dkr.ddt| W S t|dkrAt|d }d	| d
W S | ||}|rOd| W S W dS  t	yn }	 zt
dt|	  W Y d}	~	dS d}	~	ww )zP
        Analyze how the course name specifically relates to user query
        z&Course title directly addresses your 'z' objective
\b\w{3,}\br  z%Course title specifically focuses on r  r  r   zDirectly targets z development as requestedzCourse specializes in r<  z Error analyzing name relevance: N)r~  r@  r  r  r%  r  sortedlist_find_semantic_matchesr+  r#  r0  r   )
r#   r$  r  r  
name_wordsquery_word_setr  key_wordsemantic_matchesr9  r   r   r   _analyze_name_relevancee  s(   
z(TrainingAnalyzer._analyze_name_relevancecourse_skillsc              
   C   s  z|sW dS g }g }|r@dd |D }|D ]*}||v r!| | q|D ]}||v s7||v s7td|| dkr>| |  nq#qg }	|D ]}ttd|}
|
t|rZ|	 | qD|ryt|dkrld|d	  d
W S dd|dd  W S |	rt|	dkrd|	d	  dW S dd|	dd  W S |rd|d	  W S W dS  t	y } zt
dt|  W Y d}~dS d}~ww )zD
        Analyze specific skill matches and their relevance
        r<  c                 S   r  r   r  r  r   r   r   r    r  z=TrainingAnalyzer._analyze_skill_relevance.<locals>.<listcomp>NrD  r%  r  z!Precisely develops your existing r   z capabilitiesz%Enhances multiple core competencies: r  r  zBuilds essential z expertise for your goalzDevelops key competencies: r  zStrengthens related skills in z!Error analyzing skill relevance: )r*  r   r  r~  r@  r  r  r%  r  r+  r#  r0  r   )r#   r.  r  r  exact_matchespartial_matchesfiltered_skill_namesr  filtered_skillquery_skill_matchesr  r9  r   r   r   _analyze_skill_relevance  sN   

z)TrainingAnalyzer._analyze_skill_relevance
short_desc	full_descc                 C   s   zr| d| }dddddddd	d
dd
}g }|  D ]\}}||v r(|| qg }	|D ]$}
|
|v rQ||
}|dkrE|	d|
  q-|dkrQ|	d|
  q-|rb|	rb|d  d|	d  W S |ri|d W S |	rp|	d W S W dS  ty } ztdt|  W Y d}~dS d}~ww )z?
        Analyze the depth and focus of course content
        r>  z'provides practical, hands-on experiencez includes real-world project workzuses industry case studiesz$offers interactive learning approachz$includes intensive workshop sessionszfeatures realistic simulationsz#leads to professional certificationzoffers comprehensive coveragezdelivers advanced-level contentz"designed for foundational learning)
zhands-onzproject-basedz
case studyinteractiveworkshop
simulationr  r  r  beginnerr  zextensively covers r  z
addresses r   r"  r<  zError analyzing content depth: N)r  r*  countr+  r#  r0  r   )r#   r5  r6  r  content_textmethodologiesfound_methodsmethodr   query_depth_matchesr  r;  r9  r   r   r   _analyze_content_depth  sN   



z'TrainingAnalyzer._analyze_content_depthc              
      s  zc| d|  d}|r&|  }| |} fdd|D }|r&d| d}ddd	d
ddddd}	d}
|	 D ]\}}| v rJ||v rJd| }
 nq7|rW|
rW| d|
 W S |r\|W S |
ra|
W S W dS  ty } ztdt|  W Y d}~dS d}~ww )zZ
        Analyze contextual relevance including department and industry specifics
        r>  r<  c                    s   g | ]}| v r|qS r   r   r  context_textr   r   r    s    z?TrainingAnalyzer._analyze_context_relevance.<locals>.<listcomp>zspecifically designed for z professionalszenterprise-level applicationszstartup environment challengeszcorporate best practiceszagile methodologiesz"digital transformation initiativeszinnovation-driven approacheszscalable solutionszperformance optimization)
enterprisestartup	corporaterM   zdigital transformationr}   scalabilityr   zfocuses on z with z#Error analyzing context relevance: N)r?  r  r  r+  r#  r0  r   )r#   r$  r5  r  r  dept_relevancer  r  dept_matchesindustry_indicatorsindustry_contextr  contextr9  r   rB  r   _analyze_context_relevance  sH   

z+TrainingAnalyzer._analyze_context_relevancer   c           
   
      s   z_g d}g }|D ](}t ||t j}|D ]}t dd|  t fdd|D r0|  qq	|rOt|dkrBd|d  W S d	|d  d
|d  W S |dkrVW dS |dkr]W dS W dS  ty| }	 zt	
dt|	  W Y d}	~	dS d}	~	ww )zA
        Analyze expected learning outcomes and benefits
        )zyou will (?:be able to |learn to |master |understand |develop |create |implement |design |build |analyze |manage |lead |improve |optimize)([^.]+)z|(?:learn to |master |understand |develop |create |implement |design |build |analyze |manage |lead |improve |optimize)([^.]+)z'(?:enables|allows|helps) you to ([^.]+)z3(?:gain|acquire|develop|build|master|learn) ([^.]+)r=  r<  c                 3   s    | ]	}|   v V  qd S r  )r?  )r  r  clean_matchr   r   r  4  s    z>TrainingAnalyzer._analyze_learning_outcomes.<locals>.<genexpr>r  zenables you to r   zdevelops capabilities to r"  r  z&delivers high-impact learning outcomesr  z%provides measurable skill developmentz#Error analyzing learning outcomes: N)r@  r  r  rA  rB  r  r*  r%  r+  r#  r0  r   )
r#   r6  r  r   outcome_patternsoutcomesr  r  r  r9  r   rN  r   _analyze_learning_outcomes"  s2   
z+TrainingAnalyzer._analyze_learning_outcomesc                 C   s  zj| 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 ]\}}	||v r4|	} nq(d}
|  D ]\}}	||v rN||v rNd|	 }
 nq;|r[|
r[| d|
 W S |r`|W S |
rhd|
 W S W dS  ty } ztdt|  W Y d}~dS d}~ww )z>
        Analyze technical depth and complexity level
        r>  zcovers fundamental conceptsz$provides intermediate-level trainingzoffers advanced technical depthzdelivers expert-level insightszprovides comprehensive coveragezoffers in-depth explorationzdelivers specialized knowledgezcovers cutting-edge techniquesz"includes latest industry practiceszuses modern approaches)
fundamentalintermediater  r  r  zin-depthspecializedzcutting-edgelatestmodernzprogramming methodologieszdevelopment best practiceszarchitectural principleszframework implementationzdatabase optimizationzsecurity protocolszcloud technologiesz artificial intelligence conceptszmachine learning algorithmszdata science techniques)
r'   r)   architecturer6   r1   rG   r2   r;   r:   r   r<  zin zspecializes z!Error analyzing technical depth: N)r  r+  r#  r0  r   )r#   r$  r6  r  r<  depth_indicatorstech_indicatorsfound_depthr  r   
found_techr+   r9  r   r   r   _analyze_technical_depthI  s`   
z)TrainingAnalyzer._analyze_technical_depthc              
      s   zAg }|D ].}| j  D ]&\}}||kr%t fdd|D r%|| q||v r2| v r2|| qq|r?d| dW S W dS  ty^ } ztdt|  W Y d}~dS d}~ww )zE
        Find semantic matches between course name and query
        c                 3   r  r  r   )r  synr$  r   r   r    r  z:TrainingAnalyzer._find_semantic_matches.<locals>.<genexpr>r  z
 expertiser<  z Error finding semantic matches: N)	r    r  r  r*  r  r+  r#  r0  r   )r#   r$  r  r,  
query_wordr  r  r9  r   r_  r   r(    s$   
z'TrainingAnalyzer._find_semantic_matchesprimary_reasonsecondary_reasonsspecificity_detailsc           
   
   C   s"  zl|sd}|g}|r| |d  |r| |d  t|dkr%|d }n"t|dkr7|d  d|d  }n|d  d|d  d|d  }|rWt|dk rW|d	| d
7 }|dkrb|d7 }|W S |dkrj|d7 }|W S  ty }	 ztdt|	  d| d| W  Y d}	~	S d}	~	ww )zZ
            Construct a unique, detailed reason from all analyzed components
            z,Selected accordingly your query objective - r   r  r  z while r  z, and d   z
 through ''r  z (top match)rD  z (high relevance)z"Error constructing unique reason: zRecommended 'z+' for its strong alignment with your goal: N)r*  r%  r+  r#  r0  r   )
r#   ra  rb  rc  r$  r  r   reason_partsfinal_reasonr9  r   r   r   _construct_unique_reason  s4   
 z)TrainingAnalyzer._construct_unique_reasonc              	   C   sD   ddddddddd	}|  }| D ]\}}||v r|  S qd
S )zJ
        Get department-specific insights for response generation
        ztechnology leadership and digital transformation capabilities are crucial for maintaining competitive advantage in today's rapidly evolving landscape.ztechnical proficiency and software engineering excellence form the foundation for innovative solution development and system optimization.z~strategic human capital management and organizational development expertise drive employee engagement and talent optimization.zzfinancial acumen and analytical capabilities are essential for strategic decision-making and organizational fiscal health.zuprocess optimization and operational excellence methodologies ensure efficiency and sustainable business performance.zustrategic marketing competencies and customer engagement expertise are vital for brand positioning and market growth.zlrelationship management and revenue generation capabilities drive business growth and customer satisfaction.zmproduct strategy and user experience design principles are fundamental for creating market-leading solutions.r   zspecialized competencies and professional expertise are essential for achieving departmental objectives and organizational success.)r?  r  )r#   r  insightsr  r   insightr   r   r   r    s   z)TrainingAnalyzer._get_department_insightsN)0r   r   r   __doc__r$   r   r   r   r   r   r   r   r   r:  r&  r   r'  rH  r  r  r  r  r  r  r  r  r  r  r/  tupler  rI  rJ  rK  rL  r  r  r  r(  r-  r4  rA  rM  rR  r]  r(  rh  r  r   r   r   r   r      s    =
B
-34&$%."(
#3
K&g*Q<
9
3
2'<
-r   )r@  loggingtypingr   r   r   r   collectionsr   dataclassesr   difflibr   mathasynciolangchain_community.llmsr	   	getLoggerr   r#  r
   r   r   r   r   r   <module>   s    
