U
    h:                     @   s  d dl mZmZmZmZ d dlmZmZ d dlm	Z	 d dl
mZ d dlmZ d dlmZmZ d dlZd dlZd dlZd dlZd dlZejejdd	 eeZed
dZedd Zeee dddZeee dddZee dddZ!edeee ee dddZ"dS )    )capture_exceptioncapture_messageset_tagset_context)monitor_openai_apimonitor_critical_system)OpenAI)
ChatOpenAI)LangChainTracer)OptionalListNz4%(asctime)s - %(name)s - %(levelname)s - %(message)s)levelformatzopenai-cost-tracking)project_namec               
   C   s^   zddl m}  | W S  tk
rX } z(td|  t|ddi W Y dS d}~X Y nX dS )z Get OpenAI API key from settingsr   )OPENAI_API_KEYzError loading OpenAI API key: functionget_openai_api_keyN)config.settingsr   	Exceptionloggererrorr   )r   e r   ?/var/www/html/testcasegenerator.evdpl.com/ai/image_generator.pyr      s    r   )	image_urlreturnc              
   C   s\   zt | }t|jdW S  tk
rV } ztd|  W Y dS d}~X Y nX dS )z Encode image from URL to base64.utf-8zError encoding image from URL: N)	requestsgetbase64	b64encodecontentdecoder   r   r   )r   responser   r   r   r   encode_image_from_url!   s    
r$   )
image_pathr   c              
   C   sv   z8t | d$}t| dW  5 Q R  W S Q R X W n8 tk
rp } ztd|  W Y dS d}~X Y nX dS )z'Encode image from local path to base64.rbr   z Error encoding image from path: N)openr   r    readr"   r   r   r   )r%   
image_filer   r   r   r   encode_image_from_path*   s    ,r*   )	test_typer   c                 C   s   ddddddddddddd}| | | }dd	d
dddd
dddd
dddd
dddd
dddd
dd}| |i }|std|  d| d |S )z.Get the configuration for a specific test typedashboard_functionaldashboard_negativedashboard_uidashboard_uxdashboard_compatibilitydashboard_performance)r,   r-   r.   r/   r0   r1   zFunctional - Positive TestszFunctional - Negative TestzUI TestszUX TestszCompatibility TestszPerformance TestsTC_FUNCzEfunctional test cases focusing on valid inputs and expected behaviors2   )prefixdescription	max_countTC_NEGzNnegative test cases focusing on invalid inputs, error handling, and edge casesTC_UIz4UI test cases focusing on visual elements and layoutTC_UXzDuser experience test cases focusing on user interaction and workflow	TC_COMPATz@compatibility test cases across different browsers and platformsTC_PERFz@performance test cases focusing on load times and responsiveness)r,   r-   r.   r/   r0   r1   zUnknown test type: z (mapped to ))r   r   warning)r+   Zform_to_internalZinternal_typebase_configsconfigr   r   r   get_test_type_config3   sV    !r@   )r%   selected_typesr   c                    s  | st d dS |r"t|dkr0t d dS t }|rJ|dksJ|dkr`d}t | t|t d|  t d	|   d
g}ztj| sd|  }t | t	|t
|   st d W dS g }|D ]X}t d|  t|}|st d|  qd| d|d  d|d  d|d  d	d}d}	|D ]}
|rT q\zt d|
 d| d t|
d|dtgdtdd fdd }| }|j }|rt d!| d"|
  d#| d$| }|| W  q\nt d%| d"|
  W nR tk
rV } z2t|}	t d&|
 d| d'|	  W Y qBW 5 d}~X Y nX qB|s |	r d(}d)|	ksd*|	krd+| d'|	 }t | t d, td-nrd.|	 ksd/|	 krd0| d'|	 }t | t d1 td2n(d3| d4|	 }t | td5|	 t d6|  q|sHt d7 W dS t d8t| d9 d$d$| W S  tk
r } z@t jd:t| dd; t|| ||d< td=t| W 5 d}~X Y nX dS )>z9Generate test cases from an image using OpenAI Vision APIz/No image path provided for test case generationNr   z/No test types selected for test case generationyour_openai_api_key_heremissing_api_keyuA   ⚠️ Invalid or missing OPENAI_API_KEY in environment variablesz,Generating test cases from image for types: zImage path: zgpt-4ozImage file not found at path: zFailed to encode imagez#Starting generation for test type: zSkipping unknown test type: zF
            Analyze the image thoroughly and generate test cases for z (up to r6   z% maximum).
            Focus ONLY on r5   am  .
            
            IMPORTANT: Analyze the image content thoroughly and generate the appropriate number of relevant test cases.
            Consider the complexity and scope of the image - generate only what's truly needed.
            Do not force additional test cases just to reach the maximum.
            
            ANALYSIS REQUIREMENTS:
            - Analyze all visual elements: buttons, forms, text, images, icons, layout
            - Consider all possible user interactions visible in the image
            - Identify edge cases and boundary conditions
            - Consider different user roles and access levels if visible
            - Think about potential failure scenarios and error conditions
            - Analyze responsive design and cross-platform compatibility if applicable

            Use this format for each test case:

            Title: r4   a  _[Number]_[Brief_Title]
            Scenario: [Detailed scenario description covering all aspects visible in the image]
            Steps to reproduce:
            1. [Step 1]
            2. [Step 2]
            ...
            Expected Result: [What should happen]
            Priority: [High/Medium/Low]
            
            Ensure each test case covers a unique scenario and adds value.
            Focus on the most important and relevant test scenarios.
            z1Sending request to OpenAI Vision API using model z for z test casesg      ?i.  )modeltemperatureopenai_api_key
max_tokens	callbacksT)criticalc                	      s4    ddddddddd	  id
gdgS )NsystemzYou are a senior QA engineer generating test cases from the provided image. Analyze the image thoroughly and generate the appropriate number of test cases based on the image complexity. Focus on quality and relevance over quantity.)roler!   usertext)typerM   r   urlzdata:image/jpeg;base64,)rN   r   )invoker   Zbase64_imagecurrent_llmpromptr   r   make_openai_vision_call   s     z>generate_test_case_from_image.<locals>.make_openai_vision_callzSuccessfully generated z test cases using model zTEST TYPE: z

zReceived empty response for zError using model z test cases:  model_not_foundinvalid_request_errorz!Error with all OpenAI models for zYPlease check if your OpenAI account has access to gpt-4o models with vision capabilities.ziThe OpenAI model required for image processing is not available. Please check your OpenAI account access.authorizationzapi keyzAuthorization error for z6Please check your OpenAI API key in the configuration.z;OpenAI API authorization failed. Please check your API key.zError generating z test cases with all models: zFailed to generate test cases: z$Completed generation for test type: z!Failed to generate any test casesz&Successfully generated test cases for z test typesz(Error in generate_test_case_from_image: )exc_info)r%   rA   vision_modelsz*Failed to generate test cases from image: )r   r   lenr   
ValueErrorinfoospathexistsFileNotFoundErrorr*   r@   r=   r	   tracerr   r!   stripappendr   strlowerjoinr   )r%   rA   api_key	error_msgrZ   all_test_casesr+   r?   
test_cases
last_errorrD   rT   r#   test_cases_with_headerr   r   rQ   r   generate_test_case_from_imageo   s    






K
	


 







rn   )N)#utils.error_loggerr   r   r   r   utils.error_monitorr   r   openair   langchain_openair	   %langchain.callbacks.tracers.langchainr
   typingr   r   r   r   r^   sysloggingbasicConfigINFO	getLogger__name__r   rb   r   re   r$   r*   dictr@   rn   r   r   r   r   <module>   s(   



		<