o
    wh.                     @   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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 ejejd
 eeZeG dd dZeG dd dZeG dd dZeG dd dZeG dd dZeG dd dZG dd dZ G dd dZ!G dd dZ"G dd dZ#dd  Z$ed!kre$  dS dS )"    N)DictListOptionalTuple)	dataclass)SequenceMatcher)Counter)datetime)
ChatOllama)PromptTemplate)HumanMessage)levelc                   @   sB   e Zd ZU dZeed< eed< dZee ed< dZ	ee ed< dS )Skillz Data class for skill informationskill_id
skill_nameNskill_levelskill_count)
__name__
__module____qualname____doc__int__annotations__strr   r   r    r   r   R/var/www/eduai.edurigo.com/doc_train/edurigo_ai/TNA/production/tna_skill_second.pyr      s   
 r   c                   @   s>   e Zd ZU dZeed< eed< eed< eed< ee ed< dS )Coursez!Data class for course information	course_idnameshort_descriptiondescriptionskillsN)r   r   r   r   r   r   r   r   r   r   r   r      s   
 r   c                   @   sJ   e Zd ZU dZeed< eed< eed< ee ed< ee ed< eed< dS )	SkillAnalysisRequestz%Data class for skill analysis request
user_query
admin_namedepartment_namefiltered_skillsall_skills_dataall_courses_dataN)	r   r   r   r   r   r   r   r   r   r   r   r   r   r"   "   s   
 r"   c                   @   sB   e Zd ZU dZeed< eed< eed< eed< eed< eed< dS )	SkillRecommendationz#Data class for skill recommendationr   r   r   prioritysourcejustificationN)r   r   r   r   r   r   r   r   r   r   r   r)   ,   s   
 r)   c                   @   sF   e Zd ZU dZee ed< eed< eed< e	ed< eed< eed< dS )	SkillAnalysisResponsez&Data class for skill analysis responserecommended_skillsanalysis_summarydepartment_coveragetotal_skills_recommendedcase_appliedidentified_fieldN)
r   r   r   r   r   r)   r   r   floatr   r   r   r   r   r-   6   s   
 r-   c                   @   sf   e Zd ZU dZeed< eed< eed< eed< eed< eed< e	e
 ed< eed	< eed
< eed< dS )AnalysisResultz'Data class for complete analysis resultsuccessr3   r2   r1   r0   r/   r.   r#   r$   r%   N)r   r   r   r   boolr   r   r   r4   r   r)   r   r   r   r   r5   @   s   
 r5   c                   @   s  e Zd ZdZd8defddZdededefd	d
Zdedee	 dee	 fddZ
dedee dedee	 dee	 f
ddZdededee	 dee	 fddZdededee	 dee	 fddZdededee dedee f
ddZdededee dededee fddZdededededee f
ddZdededededee f
d d!Zd"edefd#d$Zd%efd&d'Zd"edefd(d)Zd*ee dee	 dee	 fd+d,Zd-edefd.d/Zd0edee fd1d2Zd3ed4edefd5d6Zd7S )9SkillInferenceEnginezJHandles skill inference using LLM with enhanced specificity-aware approach
gemma3:12b
model_namec              
   C   sN   zt |d| _td|  W dS  ty& } z	td|   d}~ww )zInitialize the LLM model)modelz"Initialized Skill LLM with model: z Failed to initialize Skill LLM: N)r
   llmloggerinfo	Exceptionerror)selfr:   er   r   r   __init__Q   s   zSkillInferenceEngine.__init__r#   r%   returnc              
   C   s   t ddgdd}z"|j||d}| jt|dg}| |j}td|  |W S  t	yL } zt
d|  d	d
g dddW  Y d}~S d}~ww )aG  
        Enhanced Step 1: Identify the field/domain with specificity analysis
        
        Args:
            user_query: User's business goal or challenge
            department_name: Target department name
            
        Returns:
            Dictionary containing field analysis with specificity information
        r#   r%   u  
            You are an expert business analyst specializing in identifying professional fields and domains.
            
            User Goal/Challenge: {user_query}
            Department: {department_name}
            
            Analyze the user's goal and provide a detailed field analysis including specificity level.
            
            SPECIFICITY LEVELS:
            - GENERAL: Broad, vague requests like "improve tech skills", "better at development", "enhance coding"
            - SPECIFIC: Domain-focused like "improve frontend skills", "better at web development", "enhance mobile development"  
            - HIGHLY_SPECIFIC: Technology-specific like "improve Angular skills", "better at React development", "enhance AWS cloud skills"
            
            ANALYSIS REQUIRED:
            1. Identify the primary professional field/domain
            2. Determine specificity level of the request
            3. Extract any specific technologies/tools mentioned
            4. Determine if this requires broad exploration or targeted learning
            
            Return your analysis in this EXACT JSON format:
            {{
                "primary_field": "specific field name",
                "specificity_level": "GENERAL|SPECIFIC|HIGHLY_SPECIFIC", 
                "key_technologies": ["tech1", "tech2"],
                "skill_focus": "broad|targeted",
                "learning_approach": "exploration|specialization|mastery"
            }}
            
            EXAMPLES:
            "improve tech skills" → {{"primary_field": "Software Development", "specificity_level": "GENERAL", "key_technologies": [], "skill_focus": "broad", "learning_approach": "exploration"}}
            
            "improve Angular skills" → {{"primary_field": "Frontend Development", "specificity_level": "HIGHLY_SPECIFIC", "key_technologies": ["Angular", "TypeScript"], "skill_focus": "targeted", "learning_approach": "mastery"}}
            
            "improve web development" → {{"primary_field": "Web Development", "specificity_level": "SPECIFIC", "key_technologies": ["HTML", "CSS", "JavaScript"], "skill_focus": "broad", "learning_approach": "specialization"}}
            
            Field Analysis:
            input_variablestemplate)r#   r%   contentzField analysis: zError in field identification: GeneralGENERALbroadexplorationprimary_fieldspecificity_levelkey_technologiesskill_focuslearning_approachN)r   formatr<   invoker   _parse_field_analysisrI   r=   r>   r?   r@   )rA   r#   r%   prompt_templateformatted_promptresponsefield_analysisrB   r   r   r   identify_field_domainZ   s.   )z*SkillInferenceEngine.identify_field_domainrZ   r'   c                 C   sh   |d }|d }|d }d dd |D }|dkr"| ||||S |dkr-| |||S | |||S )	am  
        Enhanced Step 2: Filter organizational skills based on field analysis and specificity
        
        Args:
            field_analysis: Result from identify_field_domain with specificity info
            all_skills_data: Complete list of organizational skills
            
        Returns:
            List of field-relevant organizational skills
        rO   rP   rQ   
c                 S   s&   g | ]}d |d  d|d  dqS )z- r   z (ID: r   )r   .0skillr   r   r   
<listcomp>   s    zNSkillInferenceEngine.filter_relevant_organizational_skills.<locals>.<listcomp>HIGHLY_SPECIFICSPECIFIC)join_filter_highly_specific_skills_filter_specific_skills_filter_general_skills)rA   rZ   r'   rO   rP   rQ   skills_textr   r   r   %filter_relevant_organizational_skills   s   
z:SkillInferenceEngine.filter_relevant_organizational_skillsrO   rQ   rh   c              
   C   s   d |}tg ddd}z.|j|||d}| jt|dg}| |j}	| |	|}
t	
dt|
 d|  |
W S  tyW } zt	d|  g W  Y d	}~S d	}~ww )
z5Filter skills for highly specific technology requests, )rO   rQ   rh   aL  
            HIGHLY SPECIFIC SKILL FILTERING for {primary_field}
            Target Technologies: {key_technologies}
            
            Available Skills:
            {skills_text}
            
            Since this is a HIGHLY SPECIFIC request focusing on {key_technologies}, filter skills that are:
            1. DIRECTLY related to {key_technologies} 
            2. Essential prerequisites for {key_technologies}
            3. Advanced concepts that build upon {key_technologies}
            4. Testing, debugging, or deployment tools for {key_technologies}
            5. Integration technologies that work with {key_technologies}
            
            Be VERY SELECTIVE - only include skills that have clear relevance to {key_technologies}.
            Exclude general programming concepts unless they're specifically crucial for {key_technologies}.
            
            Return ONLY the skill names that are relevant, one per line:
            - Skill Name 1
            - Skill Name 2
            ...
            
            Relevant Skills for {key_technologies}:
            rE   rH   	Filtered z highly specific skills for z*Error in highly specific skill filtering: N)rd   r   rT   r<   rU   r   _parse_skills_from_responserI   _match_skills_to_datar=   r>   lenr?   r@   )rA   rO   rQ   rh   r'   key_tech_strrW   rX   rY   relevant_skill_namesrelevant_skillsrB   r   r   r   re      s*   
z3SkillInferenceEngine._filter_highly_specific_skillsc           
   
   C      t ddgdd}z-|j||d}| jt|dg}| |j}| ||}t	dt
| d|  |W S  tyQ }	 ztd	|	  g W  Y d
}	~	S d
}	~	ww )z*Filter skills for specific domain requestsrO   rh   a  
            SPECIFIC SKILL FILTERING for {primary_field}
            
            Available Skills:
            {skills_text}
            
            Since this is a SPECIFIC domain request for {primary_field}, filter skills that are:
            1. Core skills essential to {primary_field}
            2. Common tools and technologies used in {primary_field}
            3. Methodologies and practices specific to {primary_field}
            4. Soft skills that are particularly valuable in {primary_field}
            5. Industry-standard technologies for {primary_field}
            
            Include both technical and soft skills that are domain-relevant.
            Be moderately selective - include skills that are commonly needed in {primary_field}.
            
            Return ONLY the skill names that are relevant, one per line:
            - Skill Name 1
            - Skill Name 2
            ...
            
            Relevant Skills for {primary_field}:
            rE   rO   rh   rH   rk   z specific domain skills for z#Error in specific skill filtering: Nr   rT   r<   rU   r   rl   rI   rm   r=   r>   rn   r?   r@   
rA   rO   rh   r'   rW   rX   rY   rp   rq   rB   r   r   r   rf      &   z,SkillInferenceEngine._filter_specific_skillsc           
   
   C   rr   )z(Filter skills for general broad requestsrO   rh   aP  
            GENERAL SKILL FILTERING for {primary_field}
            
            Available Skills:
            {skills_text}
            
            Since this is a GENERAL request for improving skills in {primary_field}, filter skills that are:
            1. Foundational skills that provide broad value in {primary_field}
            2. Transferable skills useful across different areas of {primary_field}
            3. Essential soft skills for {primary_field} professionals
            4. Popular tools and technologies in {primary_field}
            5. Skills that provide good career foundation in {primary_field}
            
            Be INCLUSIVE rather than restrictive - include skills that could be valuable for someone wanting to improve broadly in {primary_field}.
            Include both technical and soft skills that build a well-rounded foundation.
            
            Return ONLY the skill names that are relevant, one per line:
            - Skill Name 1
            - Skill Name 2
            ...
            
            Relevant Skills for {primary_field}:
            rE   rs   rH   rk   z general foundation skills for z"Error in general skill filtering: Nrt   ru   r   r   r   rg   %  rv   z+SkillInferenceEngine._filter_general_skillsexisting_skillsneeded_countc           
      C   st   |d }|d }|d }|d }|rd |nd}	|dkr&| ||||	|S |dkr2| |||	|S | |||	|S )	a  
        Enhanced external skill suggestion based on specificity level
        
        Args:
            user_query: User's business goal
            field_analysis: Complete field analysis with specificity info
            existing_skills: Skills already identified
            needed_count: Number of additional skills needed
            
        Returns:
            List of external skill suggestions
        rO   rP   rQ   rS   rj   Nonerb   rc   )rd   (_suggest_highly_specific_external_skills!_suggest_specific_external_skills _suggest_general_external_skills)
rA   r#   rZ   rw   rx   rO   rP   rQ   rS   existing_skills_textr   r   r   suggest_external_skillsT  s    
z,SkillInferenceEngine.suggest_external_skillsc              
   C   s   d |}tg ddd}z.|j|||||d}| jt|dg}	| |	j}
t	dt
|
 d|  |
d| W S  tyW } ztd	|  g W  Y d}~S d}~ww )
z?Suggest external skills for highly specific technology requestsrj   )r#   rO   rQ   rw   rx   a  
            HIGHLY SPECIFIC EXTERNAL SKILLS for {key_technologies}
            
            User Goal: {user_query}
            Field: {primary_field}
            Target Technologies: {key_technologies}
            Already Covered: {existing_skills}
            Skills Needed: {needed_count}
            
            Suggest {needed_count} ADVANCED and SPECIALIZED external skills specifically for {key_technologies}.
            
            Focus on:
            1. Advanced {key_technologies} concepts and patterns
            2. {key_technologies} performance optimization techniques
            3. {key_technologies} testing and debugging tools
            4. {key_technologies} deployment and CI/CD
            5. {key_technologies} ecosystem libraries and extensions
            6. Advanced architectural patterns for {key_technologies}
            7. {key_technologies} security best practices
            
            Avoid basic programming concepts - focus on skills that specifically enhance {key_technologies} expertise.
            
            Return exactly {needed_count} skills in this format:
            - External Skill 1
            - External Skill 2
            ...
            
            Advanced {key_technologies} Skills:
            rE   rH   
Suggested z% highly specific external skills for Nz4Error in highly specific external skill suggestion: )rd   r   rT   r<   rU   r   rl   rI   r=   r>   rn   r?   r@   )rA   r#   rO   rQ   rw   rx   ro   rW   rX   rY   r!   rB   r   r   r   rz   v  s,   
!z=SkillInferenceEngine._suggest_highly_specific_external_skillsc           
   
   C      t g ddd}z-|j||||d}| jt|dg}| |j}tdt	| d|  |d| W S  t
yQ }	 ztd|	  g W  Y d}	~	S d}	~	ww )	z4Suggest external skills for specific domain requestsr#   rO   rw   rx   a  
            SPECIFIC DOMAIN EXTERNAL SKILLS for {primary_field}
            
            User Goal: {user_query}
            Field: {primary_field}
            Already Covered: {existing_skills}
            Skills Needed: {needed_count}
            
            Suggest {needed_count} external skills that are trending and valuable in the {primary_field} domain.
            
            Focus on:
            1. Current industry trends in {primary_field}
            2. Emerging technologies in {primary_field}
            3. Professional best practices for {primary_field}
            4. Tools that are becoming standard in {primary_field}
            5. Skills that differentiate professionals in {primary_field}
            
            Include both technical and methodology skills relevant to {primary_field}.
            
            Return exactly {needed_count} skills in this format:
            - External Skill 1
            - External Skill 2
            ...
            
            Trending {primary_field} Skills:
            rE   rH   r   z% specific domain external skills for Nz-Error in specific external skill suggestion: r   rT   r<   rU   r   rl   rI   r=   r>   rn   r?   r@   
rA   r#   rO   rw   rx   rW   rX   rY   r!   rB   r   r   r   r{     (   z6SkillInferenceEngine._suggest_specific_external_skillsc           
   
   C   r   )	z2Suggest external skills for general broad requestsr   af  
            GENERAL FOUNDATIONAL EXTERNAL SKILLS for {primary_field}
            
            User Goal: {user_query}
            Field: {primary_field}
            Already Covered: {existing_skills}
            Skills Needed: {needed_count}
            
            Suggest {needed_count} diverse external skills that provide a strong foundation across {primary_field}.
            
            Focus on:
            1. Fundamental skills every {primary_field} professional should have
            2. Cross-cutting skills that apply to multiple areas of {primary_field}
            3. Soft skills essential for {primary_field} success
            4. Basic tools and technologies that are widely used in {primary_field}
            5. Skills that provide good career versatility in {primary_field}
            
            Provide a well-rounded mix of technical, methodological, and soft skills.
            
            Return exactly {needed_count} skills in this format:
            - External Skill 1
            - External Skill 2
            ...
            
            Foundation {primary_field} Skills:
            rE   rH   r   z( general foundation external skills for Nz,Error in general external skill suggestion: r   r   r   r   r   r|     r   z5SkillInferenceEngine._suggest_general_external_skillsresponse_contentc           	   
   C   s   ddl }ddl}z.|d||j}|r1|| }g d}|D ]}||vr-| |||< q |W S | |W S  tyX } zt	
d|  ddg dd	dW  Y d}~S d}~ww )
z&Parse field analysis from LLM responser   Nz\{.*\}rN   zError parsing field analysis: rJ   rK   rL   rM   )jsonresearchDOTALLloadsgroup_get_default_value_fallback_field_analysisr?   r=   r@   )	rA   r   r   r   
json_matchrZ   required_fieldsfieldrB   r   r   r   rV     s.   z*SkillInferenceEngine._parse_field_analysis
field_namec                 C   s   ddg ddd}| |dS )z%Get default values for missing fieldsrJ   rK   rL   rM   rN    )get)rA   r   defaultsr   r   r   r   3  s   z'SkillInferenceEngine._get_default_valuec                    sv   |   t fdddD rd}d}d}nt fdddD r(d	}d
}d}nd}d
}d}| |}||g ||dS )z+Fallback parsing when JSON extraction failsc                 3       | ]}| v V  qd S Nr   )r_   techcontent_lowerr   r   	<genexpr>D      z@SkillInferenceEngine._fallback_field_analysis.<locals>.<genexpr>)angularreactvuepythonjavaawsdockerrb   targetedmasteryc                 3   r   r   r   )r_   domainr   r   r   r   H  r   )zweb developmentzmobile developmentzdata sciencefrontendbackendrc   rL   specializationrK   rM   rN   )lowerany_clean_field_name)rA   r   specificityfocusapproachr   r   r   r   r   >  s&   
z-SkillInferenceEngine._fallback_field_analysisskill_namesc                 C   s:   g }|D ]}|D ]}|  ||d r||  nqq|S )z-Match skill names back to original skill datar   )_skills_matchappend)rA   r   r'   rq   r   	org_skillr   r   r   rm   \  s   
z*SkillInferenceEngine._match_skills_to_data
field_textc                 C   s<   |  dd }|dddddd}| d}|S )zClean and normalize field namer\   r   zField/Domain:r   zField:zDomain:z "')stripsplitreplace)rA   r   r   r   r   r   f  s   
z&SkillInferenceEngine._clean_field_nameresponse_textc                 C   sX   g }|  d}|D ]}|  }tdd|}|  }|r)t|dkr)|| q|S )zParse skills from LLM responser\   u   ^[-•*\d+\.\)]\s*r      )r   r   r   subrn   r   )rA   r   r!   linesliner   r   r   rl   m  s   
z0SkillInferenceEngine._parse_skills_from_responseskill1skill2c                 C   sl   t dd|  }t dd|  }||krdS td|| }|dkr*dS ||v s2||v r4dS dS )z9Check if two skill names match with reasonable similarityz[^a-zA-Z0-9\s]r   TNg?F)r   r   r   r   r   ratio)rA   r   r   skill1_normskill2_norm
similarityr   r   r   r   |  s   z"SkillInferenceEngine._skills_matchNr9   )r   r   r   r   r   rC   dictr[   r   r   ri   re   rf   rg   r   r~   rz   r{   r|   rV   r   r   rm   r   rl   r7   r   r   r   r   r   r8   N   s~    	K


3

/

/

"

9

2
2 "
r8   c                	   @   s6   e Zd ZdZe	d	dee dedee fddZdS )
SkillMatcherz/Handles skill matching and filtering operations      ?r&   coverage_thresholdrD   c                 C   sl   | sg S t dd | D dd}g }| D ]}|j| }||k r#|| qtdt| dt|  d |S )aK  
        Filter out skills that are already well-covered in the department
        
        Args:
            filtered_skills: Current department skills with counts
            coverage_threshold: Threshold for considering a skill well-covered
            
        Returns:
            List of skills that need improvement
        c                 S      g | ]}|j qS r   r   r^   r   r   r   ra         z9SkillMatcher.filter_department_skills.<locals>.<listcomp>   )defaultrk   z under-covered skills from z total skills)maxr   r   r=   r>   rn   )r&   r   total_employeesunder_covered_skillsr`   coverage_ratior   r   r   filter_department_skills  s   

 z%SkillMatcher.filter_department_skillsN)r   )	r   r   r   r   staticmethodr   r   r4   r   r   r   r   r   r     s    r   c                   @   s   e Zd ZdZdd ZdedefddZdedefdd	Z	d
e
e dedefddZd
e
e deeef fddZdedefddZdS )TNAPresentationz8Handles presentation of TNA analysis in multiple formatsc                 C   s   t d dS )z"Initialize the presentation systemz#TNA Presentation System initializedN)r=   r>   )rA   r   r   r   rC     s   zTNAPresentation.__init__analysis_resultrD   c                 C   s   g }|j D ]}||j|j|j|j|j|jd q|j|j	|j
|jt|jd|j||j|j|jt  tdd |j D tdd |j D | |j dd}td |S )	z
        Generate raw analysis output in JSON format
        
        Args:
            analysis_result: Complete analysis result
            
        Returns:
            Dictionary with raw analysis data
        r   r   r   r*   r+   r,      c                 S      g | ]	}|j d kr|qS organizational_relevantr+   r_   sr   r   r   ra         z9TNAPresentation.generate_raw_analysis.<locals>.<listcomp>c                 S   r   externalr   r   r   r   r   ra     r   )r#   r$   r%   analysis_timestamptotal_organizational_skillstotal_external_skillspriority_breakdown)r6   r3   r2   r1   r0   r/   r.   metadataz#Raw analysis generated successfully)r.   r   r   r   r   r*   r+   r,   r6   r3   r2   r1   roundr0   r/   r#   r$   r%   r	   now	isoformatrn   _get_priority_breakdownr=   r>   )rA   r   skills_jsonr`   raw_analysisr   r   r   generate_raw_analysis  s8   






z%TNAPresentation.generate_raw_analysisc              	   C   s  dd |j D }dd |j D }dd |j D }|j r&t|t|j  d nd}t d}dg d	|j d
|j d|j d|j d|j	  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t||  dt||  d dd!d || dd D  d"dd#d |dd D  d$|j	  d%| d&|jrd'nd( d)|dd*}td+ |S ),z
        Generate strategic executive presentation
        
        Args:
            analysis_result: Complete analysis result
            
        Returns:
            Formatted string with strategic presentation
        c                 S   r   r   r   r   r   r   r   ra     r   zCTNAPresentation.generate_strategic_presentation.<locals>.<listcomp>c                 S   r   r   r   r   r   r   r   ra     r   c                 S   r   )department_existingr   r   r   r   r   ra     r   d   r   z	%B %d, %Yr   z
 Hello z,

We noticed you shared: "u:   ". That’s a great growth mindset! Wanting to improve in u    shows real initiative.

 Here’s what we’ve analyzed and suggest for you:

━━━━━━━━━━━━━━━━━━━━━━━  
 What You Need to Grow in ud     
━━━━━━━━━━━━━━━━━━━━━━━  

To really level up your z skills, we identified a combination of organizational skills you already have access to, plus some external skills that will give you an extra edge.

 Core Organizational Skills You Can Start With:
organizationalu   

These are skills already available internally through your organization’s resources. It’s like already having some tools in your toolbox!

High-Value External Skills That Unlock the Next Level:
r   u  

These are the more advanced or specialized areas where external training, certifications, or hands-on projects could make a big difference.

━━━━━━━━━━━━━━━━━━━━━━━  
 Prioritized Skill Recommendations  
━━━━━━━━━━━━━━━━━━━━━━━  

Based on your profile and our analysis, here’s a practical order to focus on:

1️ Most Important – Start Here:
rj   c                 S   r   r   r   r   r   r   r   ra     r   N   u   

Why? You already have access to resources for these. Quick wins, low setup time, high ROI.

2️ Secondary Focus – Build Deeper Expertise:
c                 S   r   r   r   r   r   r   r   ra     r   uy   

These are high-impact but need external support or new learning paths.

3️ Bonus Round – Become Truly Unstoppable:
c                 S   r   r   r   r   r   r   r   ra     r      uV  

Once you’ve mastered the core and secondary skills, these will push your capabilities into the top professional bracket.

━━━━━━━━━━━━━━━━━━━━━━━  
 Your Current Capability Assessment  
━━━━━━━━━━━━━━━━━━━━━━━  

- Skill Match with Organization: z.1fz%  
- Existing Skills Found: u>     

Good news — you already have a solid foundation! Having u   relevant skills puts you one step ahead.

━━━━━━━━━━━━━━━━━━━━━━━  
 Suggested Learning Path  
━━━━━━━━━━━━━━━━━━━━━━━  

Phase 1 (0–3 Months): Strengthen Existing Skills  
- Focus on c                 S   r   r   r   r   r   r   r   ra   -  r   u     
- Use internal training programs  
- Regular check-ins to track progress  

 Phase 2 (3–6 Months): Expand with External Skills  
- Focus on c                 S   r   r   r   r   r   r   r   ra   2  r   u    
- Plan for external courses, certifications, or mentorship  
- Budget allocation and resource setup required  

━━━━━━━━━━━━━━━━━━━━━━━  
 Final Thoughts  
━━━━━━━━━━━━━━━━━━━━━━━  

You’ve already taken the first step by identifying your goal. Now with this structured plan, you’re on the path to mastering u5   .

Let’s keep the momentum going!  

Generated on: z  
Analysis Confidence: HighLowz  
Resource Utilization: u    %

— TNA v2.0 Insights Engine
z-Strategic presentation generated successfully)r.   rn   r	   r   strftimerd   r$   r#   r3   r   _format_skill_sectionr6   r=   r>   )rA   r   
org_skills
ext_skillsdept_skillsorg_percentagecurrent_datestrategic_reportr   r   r   generate_strategic_presentation  s\    

#(0

1
3:?GKLM
Tz/TNAPresentation.generate_strategic_presentationr!   section_typec              	   C   sL   |sdS g }t |dD ]\}}||dd|j d|j d qd|S )z0Format skills section for strategic presentationz&No skills identified in this category.r   2d.  (r]   r\   )	enumerater   r   r   rd   )rA   r!   r   formatted_skillsir`   r   r   r   r   J  s   $
z%TNAPresentation._format_skill_sectionc                 C   s6   dddd}|D ]}|j |v r||j   d7  < q|S )z#Get breakdown of skills by priorityr   )r   Mediumr   r   )r*   )rA   r!   	breakdownr`   r   r   r   r   U  s   
z'TNAPresentation._get_priority_breakdownc                 C   s   |  || |dS )z
        Generate both raw and strategic formats
        
        Args:
            analysis_result: Complete analysis result
            
        Returns:
            Dictionary containing both formats
        r   strategic_presentation)r   r   )rA   r   r   r   r   generate_both_formats]  s   z%TNAPresentation.generate_both_formatsN)r   r   r   r   rC   r5   r   r   r   r   r   r)   r   r   r   r  r   r   r   r   r     s    ,jr   c                	   @   s   e Zd ZdZddefddZdedefdd	Zd
e	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	fddZdedefddZdedefddZddededeeef fddZdS )SkillAnalysisSystemzCMain Skill Analysis System with enhanced specificity-aware approachr9   r:   c                 C   s.   t || _t | _t | _d| _td dS )z$Initialize the skill analysis system   z<Enhanced Specificity-Aware Skill Analysis System initializedN)	r8   skill_enginer   skill_matcherr   	presentermin_skills_targetr=   r>   )rA   r:   r   r   r   rC   o  s
   
zSkillAnalysisSystem.__init__request_datarD   c                 C   s   z9|  |}| j|j|jpd}| j||j}|jr2|j dkr2t|j	dkr2| 
|||W S | |||W S  tyb } ztd|  tg dt| dddd	d
W  Y d}~S d}~ww )a  
        Main method to analyze skills using enhanced specificity-aware approach
        
        Args:
            request_data: Dictionary containing all necessary data
            
        Returns:
            SkillAnalysisResponse with recommendations
        rJ   nullr   zError in skill analysis: zError in analysis:         r   ErrorUnknownr.   r/   r0   r1   r2   r3   N)_parse_requestr
  r[   r#   r%   ri   r'   r   rn   r&   _handle_case_1_improved_handle_case_2_improvedr?   r=   r@   r-   r   )rA   r  requestrZ   relevant_org_skillsrB   r   r   r   analyze_skillsx  s6   

z"SkillAnalysisSystem.analyze_skillsr  rZ   r  c                 C   s  t d |d }|d }g }t }| jj|jdd}|D ].}	|	j|vrK|t|	j|	j	|	j
p/dddd	|	j d
tdd |jD  d ||	j q|D ])}
|
d |vrw|t|
d |
d dddd| d|  dd ||
d  qNt|| jk r| jt| }dd |D }| j|j|||}t|D ]\}}|td| |dddd|  d| dd q|jrt|t|j nd}t|d| j d|j d | d| d!t| d"	|t|d| j d#|d$S )%zq
        Handle Case 1 with enhanced specificity-aware approach: Department found AND employee count > 3
        zFApplying Case 1 (Enhanced): Department found with sufficient employeesrO   rP   r   )r   Intermediater   r   zUnder-covered in department: z employees out of c                 S   r   r   r   r   r   r   r   ra     r   z?SkillAnalysisSystem._handle_case_1_improved.<locals>.<listcomp>r   r   r   r  r   Relevant to  field (% level) and available in organizationc                 S   r   r   r   r_   recr   r   r   ra     r   (#  Beginnerr   r   	External  skill for z to enhance capabilitiesr   NzEnhanced analysis for z department in 	). Found   relevant organizational skills.z=Case 1 (Enhanced): Department found with sufficient employeesr  )r=   r>   setr  r   r&   r   r   r)   r   r   r   r   addr   rn   r  r
  r~   r#   r   r-   r%   )rA   r  rZ   r  r3   rP   recommendationsused_skill_idsunder_covered_dept_skills
dept_skillr   rx   existing_skill_namesexternal_skillsr  	ext_skilldept_coverager   r   r   r    sx   

 

"z+SkillAnalysisSystem._handle_case_1_improvedc                 C   s@  t d |d }|d }g }t }|D ])}|d |vr=|t|d |d dddd	| d
|  dd ||d  qt|| jk r~| jt| }	dd |D }
| j	
|j||
|	}t|D ]\}}|td| |dddd|  d| dd qat|d| j d| d
| dt| ddt|d| j d|dS )uv   
        Handle Case 2 with enhanced specificity-aware approach: Department not found OR employee count ≤ 3
        zJApplying Case 2 (Enhanced): Department not found or insufficient employeesrO   rP   r   r   r  r  r   r  r  r  r   c                 S   r   r   r   r  r   r   r   ra     r   z?SkillAnalysisSystem._handle_case_2_improved.<locals>.<listcomp>r   r!  r   r   r"  r#  z to fill capability gapNzEnhanced general analysis for r$  r%  r  zACase 2 (Enhanced): Department not found or insufficient employeesr  )r=   r>   r&  r   r)   r   r'  rn   r  r
  r~   r#   r   r-   )rA   r  rZ   r  r3   rP   r(  r)  r   rx   r,  r-  r  r.  r   r   r   r    sV   

	z+SkillAnalysisSystem._handle_case_2_improvedc              
   C   st   g }d|v r"|d D ]}| t|d |d |d|dd q
t|d |d |d	 ||d
g |di dS )z3Parse request data into SkillAnalysisRequest objectr&   r   r   r   r   r   r   r   r   r#   r$   r%   r'   r(   r#   r$   r%   r&   r'   r(   )r   r   r   r"   )rA   r  r&   
skill_datar   r   r   r  /  s"   


z"SkillAnalysisSystem._parse_request	json_datac              
   C   s   z7t |}| |}g }|jD ]}||j|j|j|j|j	|j
d qd|j||jt|jd|j|jdW S  t jy[ } ztd|  dd| g dW  Y d	}~S d	}~w ty| } ztd
|  dt|g dW  Y d	}~S d	}~ww )z
        Process JSON request and return JSON response (Raw format only)
        
        Args:
            json_data: JSON string with request data
            
        Returns:
            Dictionary with response data
        r   Tr   )r6   r3   r.   r/   r0   r1   r2   JSON decode error: FInvalid JSON format: r6   r@   r.   NProcessing error: )r   r   r  r.   r   r   r   r   r*   r+   r,   r3   r/   r   r0   r1   r2   JSONDecodeErrorr=   r@   r?   r   )rA   r3  r  rY   recommendations_jsonr  rB   r   r   r   process_json_requestE  sH   







z(SkillAnalysisSystem.process_json_requestc                 C   s  z2t |}| |}td|j|j|j|j|j|j	|d |d |d d
}| j
|}td |W S  t jy\ } ztd|  dd	| g d
d| dW  Y d}~S d}~w ty } ztd|  dt|g d
dt| dW  Y d}~S d}~ww )z
        Process JSON request and return BOTH raw and strategic formats
        
        Args:
            json_data: JSON string with request data
            
        Returns:
            Dictionary with both presentation formats
        Tr#   r$   r%   
r6   r3   r2   r1   r0   r/   r.   r#   r$   r%   z0Both presentation formats generated successfullyr4  Fr5  r6  zError: Invalid JSON format - r  Nr7  zError: )r   r   r  r5   r3   r2   r1   r0   r/   r.   r  r  r=   r>   r8  r@   r?   r   )rA   r3  r  analysis_responser   both_formatsrB   r   r   r   process_with_both_formatsx  sJ   



z-SkillAnalysisSystem.process_with_both_formatstna_analysisfilename_prefixc                 C   sj  zt |}| |}td|j|j|j|j|j|j	|d |d |d d
}t
 d}| j|}| d| d}t|d	d
d}	t j|d |	ddd W d   n1 sWw   Y  | d| d}
t|
d	d
d}	|	|d  W d   n1 s}w   Y  td| d|
  ||
ddW S  ty } ztd|  dt|dW  Y d}~S d}~ww )a  
        Process analysis and save both formats to files
        
        Args:
            json_data: JSON string with request data
            filename_prefix: Prefix for saved files
            
        Returns:
            Dictionary with file paths
        Tr#   r$   r%   r;  z%Y%m%d_%H%M%S_raw_z.jsonwzutf-8)encodingr   r   F)indentensure_asciiN_strategic_z.txtr  zAnalysis saved to z and )raw_filestrategic_filer6   zError saving analysis: )r6   r@   )r   r   r  r5   r3   r2   r1   r0   r/   r.   r	   r   r   r  r  opendumpwriter=   r>   r?   r@   r   )rA   r3  r@  r  r<  r   	timestampr=  raw_filenamefstrategic_filenamerB   r   r   r   save_analysis_report  sJ   

z(SkillAnalysisSystem.save_analysis_reportNr   )r?  )r   r   r   r   r   rC   r   r-   r  r"   r   r   r  r  r  r:  r>  rP  r   r   r   r   r  l  s,    	.
O
:3$7r  c            
      C   s  t  } ddddddddd	d
dddg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gd$d%d&d&d'g d(d)gid*}d+dddddddd	d
dddgddddd,ddd-ddddddddddd d.dd"d/dgd$d%d0d1d'g d2d)gid*}td3 td4 td3 td5 td6 td7 | t|}td8|d9   td:|d;   td<|d=   td> t|d? d@D ]\}}t| dA|dB  dC|dD  dE|dF   qtd5 tdG td7 | t|}td8|d9   td:|d;   td<|d=   td> t|d? d@D ]\}}t| dA|dB  dC|dD  dE|dF   q)tdH tdI td3 tdJ t|}| |}|dK }	t|	 dLS )Mz:Example usage of the Enhanced Specificity-Aware TNA Systemz'Want to improve my Python skill abilityAscent	Developerx   Pythonr  r   r0  i  zEmotional IntelligenceAdvancedr   il  znegotiation and closure)r   r   im  zmarket analysisin  zproduct knowledgey   
JavaScriptz   React{   zNode.js|   HTML}   CSS~   SQL   Git   Docker373zJava Courser   )r   
javascriptcoding)courseIdr   r   r    r!   r1  z!Want to improve my Angular skills
TypeScriptAngularzVue.jsRxJSzAngular Advanced CoursezAdvanced Angular Development)r   
typescriptrxjszP================================================================================z3ENHANCED SPECIFICITY-AWARE TNA SYSTEM DEMONSTRATIONz3
==================================================z0TEST 1: GENERAL QUERY - 'improve python ability'z2==================================================zField Identified: r3   zTotal Skills: r1   z	Summary: r/   z
Top 5 Recommended Skills:r.   r   r   r   r   r+   z) - r,   z8TEST 2: HIGHLY SPECIFIC QUERY - 'improve Angular skills'zQ
================================================================================zmENHANCEMENT SUCCESS: Different queries now produce different, contextually appropriate skill recommendations!	Strategicr  N)r  printr:  r   dumpsr   r>  )
skill_systemsample_request_generalsample_request_specificgeneral_resultr  r`   specific_resultr3  resultr   r   r   r   main  s   -),.

rx  __main__)%r   loggingtypingr   r   r   r   dataclassesr   difflibr   r   collectionsr   r	   langchain_ollamar
   langchain.promptsr   langchain.schemar   basicConfigINFO	getLoggerr   r=   r   r   r"   r)   r-   r5   r8   r   r   r  rx  r   r   r   r   <module>   sT    
			    C  @    
