o
    Jth]                     @   s   d dl Z d dlZd dlmZmZ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G dd dZdd Zedkree  dS dS )    N)DictListOptional)	dataclass)
ChatOllama)PromptTemplate)HumanMessage)levelc                   @   s:   e Zd ZU dZeed< eed< eed< eed< eed< dS )Coursez!Data class for course information	course_idnameshort_descriptiondescriptionskillN)__name__
__module____qualname____doc__str__annotations__ r   r   R/var/www/eduai.edurigo.com/doc_train/edurigo_ai/TNA/production/tna_course_trial.pyr
      s   
 r
   c                   @   s&   e Zd ZU dZeed< ee ed< dS )CourseFilterRequestz'Data class for course filtering requestidentified_fieldcoursesN)r   r   r   r   r   r   r   r
   r   r   r   r   r      s   
 r   c                   @   s>   e Zd ZU dZeed< eed< ee ed< eed< eed< dS )CourseFilterResponsez(Data class for course filtering responser   total_courses_inputmatching_coursestotal_matching_coursesfiltering_reasoningN)	r   r   r   r   r   r   intr   r
   r   r   r   r   r      s   
 r   c                   @   s   e Zd ZdZddefddZdedee defd	d
Z	dee defddZ
de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edefddZdS )CourseFieldIdentifierz<Handles course filtering based on identified field using LLM
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 course field identifier)modelz0Course Field Identifier initialized with model: z.Failed to initialize Course Field Identifier: N)r   llmloggerinfo	Exceptionerror)selfr#   er   r   r   __init__(   s   zCourseFieldIdentifier.__init__r   r   returnc                    s   z4|  |}| ||\ } fdd|D }t|t||t||d}tdt| d| d |W S  ty^ } ztd|  t|t|g dd	t| dW  Y d
}~S d
}~ww )aX  
        Filter courses that match the identified field using LLM analysis
        
        Args:
            identified_field: The field identified from skill analysis (e.g., "Frontend Development")
            courses: List of all available courses
            
        Returns:
            CourseFilterResponse with matching courses
        c                    s   g | ]	}|j  v r|qS r   )r   ).0coursematching_course_idsr   r   
<listcomp>F   s
    
zACourseFieldIdentifier.filter_courses_by_field.<locals>.<listcomp>)r   r   r   r   r   z	Filtered z courses for z fieldzError in course filtering: r   zError in filtering: N)	_format_courses_for_llm_get_llm_course_analysisr   lenr&   r'   r(   r)   r   )r*   r   r   courses_text	reasoningr   responser+   r   r0   r   filter_courses_by_field1   s8   

z-CourseFieldIdentifier.filter_courses_by_fieldc                 C   sz   g }|D ]3}|j  }|jr|d|j 7 }|jr |d|j 7 }|jr+|d|j 7 }|d|j d|  qd|S )z!Format courses data for LLM inputz - z | z | Skills: zID: 
)r   r   r   r   appendr   join)r*   r   courses_formattedr/   full_descriptionr   r   r   r3   `   s   
z-CourseFieldIdentifier._format_courses_for_llmr6   c           
   
   C   s   t ddgdd}z3|j||d}| jt|dg}| |j}|dg }|dd	}t	d
t
| d ||fW S  ty^ }	 ztd|	  g dt|	 fW  Y d}	~	S d}	~	ww )z<Get LLM analysis of which courses match the identified fieldr   r6   ai  
            You are an EXPERT course curator. Be VERY STRICT in matching courses to the field.
            
            TARGET FIELD: {identified_field}
            
            COURSES TO EVALUATE:
            {courses_text}
            
            STRICT MATCHING CRITERIA:
            
            For {identified_field} field, ONLY approve courses that:
            1. Directly teach {identified_field} skills and knowledge
            2. Use tools/technologies commonly used in {identified_field}
            3. Solve real problems that {identified_field} professionals face
            4. Build competencies essential for {identified_field} roles
            
            DEFINITELY REJECT:
            - Courses from completely different fields (e.g., Programming courses for Sales)
            - General knowledge or academic subjects not job-relevant
            - Courses too basic/generic to help {identified_field} professionals
            - Administrative, testing, or demo content
            
            EXAMPLES FOR DIFFERENT FIELDS:
            
            Sales Field - APPROVE: "Sales Techniques", "CRM Training", "Negotiation Skills", "Customer Relations"
            Sales Field - REJECT: "Python Programming", "Angular Development", "Database Administration"
            
            Frontend Development - APPROVE: "Angular", "React", "JavaScript", "HTML/CSS", "UI/UX"
            Frontend Development - REJECT: "Sales Training", "HR Management", "Accounting Principles"
            
            BE EXTREMELY SELECTIVE. When in doubt, REJECT the course.
            
            Return JSON:
            {{
                "matching_course_ids": ["id1", "id2"],
                "reasoning": "Detailed explanation of why specific courses were selected/rejected for {identified_field}"
            }}
            
            Analysis for {identified_field}:
            )input_variablestemplate)r   r6   )contentr1   r7   zLLM analysis completedzLLM identified z matching courseszError in LLM course analysis: zError in LLM analysis: N)r   formatr%   invoker   _parse_llm_responserA   getr&   r'   r5   r(   r)   r   )
r*   r   r6   prompt_templateformatted_promptr8   analysis_resultr1   r7   r+   r   r   r   r4   r   s(   ,
z.CourseFieldIdentifier._get_llm_course_analysisresponse_contentc              
   C   s   z"ddl }|d||j}|rt| }d|v r|W S | |W S  tjyB } zt	d|  | |W  Y d}~S d}~w t
y` } ztd|  g ddW  Y d}~S d}~ww )	z6Parse LLM response to extract course IDs and reasoningr   Nz\{.*\}r1   zJSON parsing failed: zError parsing LLM response: zFailed to parse LLM responser1   r7   )researchDOTALLjsonloadsgroup_fallback_parse_responseJSONDecodeErrorr&   warningr(   r)   )r*   rI   rK   
json_matchparsed_responser+   r   r   r   rD      s"   z)CourseFieldIdentifier._parse_llm_responsec                 C   sN   ddl }g d}g }|D ]}||||j}|| qtt|}|ddS )z+Fallback parsing when JSON extraction failsr   N)zID:\s*(\w+)zCourse\s*(\w+)z^\s*(\w+)\s*-z:Extracted course IDs from text response (fallback parsing)rJ   )rK   findall	MULTILINEextendlistset)r*   rI   rK   course_id_patternsmatching_idspatternmatchesr   r   r   rQ      s   z.CourseFieldIdentifier._fallback_parse_response	json_datac              
   C   sn  zqt |}|dd}|sddg dW S |dg }g }|D ]&}tt|dd|dd|d	d|d
d|ddd}|| q| ||}g }	|jD ]}|	|j|j	|j
|j|jd qQd|j|j|	|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
        
        Args:
            json_data: JSON string with identified_field and courses data
            
        Returns:
            Dictionary with filtered courses
        r    FzNo identified_field provided)successr)   r   r   r   course_namecourse_short_descriptioncourse_descriptionr   )r   r   r   r   r   r   rb   rc   rd   r   T)ra   r   r   r   r   r   zJSON decode error: zInvalid JSON format: NzProcessing error: )rN   rO   rE   r
   r   r;   r9   r   r   r   r   r   r   r   r   r   r   rR   r&   r)   r(   )r*   r_   request_datar   courses_datar   course_datar/   filter_responsematching_courses_jsonr+   r   r   r   process_json_request   sf   






		z*CourseFieldIdentifier.process_json_requestN)r"   )r   r   r   r   r   r,   r   r
   r   r9   r3   tupler4   r   rD   rQ   rk   r   r   r   r   r!   %   s    	/Dr!   c                  C   s  t  } dg ddddg dddddg ddd	d	dg dd
dddg dddddg dddddg dddddg dddddg dddddg dddddg ddddd g dd!d"d"dg dd#d$d%d&g dd'd(d(d)g dd*d+d+d,g dd-d.d.dg dd/d0d1d2g dd3d4d4dg dd5d6d6dg dd7d8d8dg dd9d:d:dg dd;d<d<dg dd=d>d?d@g ddAdBdCdg ddDdEdEdg ddFdGdGdg ddHdIdJdg ddKdLdLdg ddMdNdNdg ddOdPdPdg ddQdRdSdg ddTdUdUdg ddVdWdXdYdZd[d\}td] td^|d_   td`t|da   tdb | t|}|dc rtdd tde|d_   tdf|dg   tdh|di   tdj|dk   tdl t|dm dnD ]+\}}t| do|dp  dq|dr  ds tdt|du   tdv|dw   t  qln	tdx|dy   tdz | }d{|d_< td| tdb | t|}|dc rtdd tde|d_   tdh|di   tdl t|dm dnD ]\}}t| do|dp  dq|dr  ds qd}S d}S )~z3Example usage of the Course Field Identifier SystemzSales 32zGeneral Knowledger`   )r   rb   rc   rd   skills33zCurrent Affairs43z*Python Programming for Complete Beginners 58zLaravel BeginnerzLaravel Beginner description 59zCodeigntier BeginnerzCodeigntier Beginner short desc60zNew CCourse zNew COurse short desc63zAngular BasiczAngular is a platform and framework for building single-page client applications using HTML and TypeScript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your applicatab  <p>Angular is a platform and framework for building single-page client applications using HTML and TypeScript. Angular is written in TypeScript. It implements core and optional functionality as a set of TypeScript libraries that you import into your applications.<\/p><p>The architecture of an Angular application relies on certain fundamental concepts. The basic building blocks of the Angular framework are Angular components that are organized into <i>NgModules<\/i>. NgModules collect related code into functional sets; an Angular application is defined by a set of NgModules. An application always has at least a <i>root module<\/i> that enables bootstrapping, and typically has many more <i>feature modules<\/i>.<\/p><p>Components define <i>views<\/i>, which are sets of screen elements that Angular can choose among and modify according to your program logic and data.<\/p><p>Components use <i>services<\/i>, which provide specific functionality not directly related to views. Service providers can be <i>injected<\/i> into components as <i>dependencies<\/i>, making your code modular, reusable, and efficient.<\/p>64zLeadership Chapter 165Sorting66zCSS Selectorz-<ul><li>CSS Selector<\/li><li>css<\/li><\/ul>68zsimple coursea9  <ol><li><strong>Lorem Ipsum<\/strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.<\/li><li>hhgh<\/li><li>hjhjhj<\/li><\/ol>69zreport testing70zAuthor CoursezAuthor Coursesz<p>Author Course<\/p>71zDemo Coursez<p>Demo Course<\/p>72zCourse By Authorz<p>Course By Author<\/p>73zJava Course90zMath Quiz Coursez	Math Quizz<p>All quiz course<\/p>92zAll Quiz Test93zMath Course94zScorm Posh Course95zScorm Info Security96zquiz analysis97zquiz analysis testzquiz analysis short descz<p>description<\/p>98zcreate coursezcourse desc99zQuiz Test Course100z
new course103zScorm WarehousezNew Scorm Course104zLeading Yourself Scorm135zCertificate test136zCertificate Test 2138ASD12ASD21141Tester6zDatabase AdministrationzSQL and database managementz?Learn database design, SQL queries, and database administrationzsql, database, administrationre   )r   r   z)Processing Course Field Identification...zIdentified Field: r   zTotal Input Courses: r   z2--------------------------------------------------ra   u   ✅ SUCCESSzField: zInput Courses: r   zMatching Courses: r   zReasoning: r   u   
📚 MATCHING COURSES:r      z. rb   z (ID: r   )z   Description: rc   z   Skills: r   u   ❌ ERROR: r)   z<============================================================zData Sciencez+
Testing with different field: Data ScienceN)r!   printr5   rk   rN   dumps	enumeratecopy)course_identifiersample_requestresultir/   sample_request_2result_2r   r   r   main6  sV  	%,3:AHOV]dkry          $  +  2  9  @  G  N  U  \  c  o
"

&r   __main__)rN   loggingtypingr   r   r   dataclassesr   langchain_ollamar   langchain.promptsr   langchain.schemar   basicConfigINFO	getLoggerr   r&   r
   r   r   r!   r   r   r   r   r   <module>   s0    
    $
