o
    ,fr.                     @   s  d dl mZmZmZmZmZmZmZ d dlZd dl	m
Z
 d dlZd dl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mZmZ d dlZd dlmZmZ d ad aejejd ee Z!ee Z"e
 Z#d	e_$d
diZ%e"&ddd Z'e"&ddd Z(e#j)dd Z)e"j&dddgde#j*dd Z+e"&de#j*dd Z,dd Z-dd  Z.d!d" Z/d#d$ Z0d%d& Z1d'd( Z2d)d* Z3d+d, Z4d-d. Z5e d/kre"j6d0d1 dS dS )2    )ResponseFlaskrequestrender_template	send_fileredirecturl_forN)HTTPBasicAuth)BeautifulSoup)urljoinurlparse)StringIOBytesIO)r   parse_qs)levelz8sk-proj-g5KUovMAPblK2YVhYFWYT3BlbkFJbRnn3OubcnZrWyodkjQkZadminZsecretz/favicon.icoc                   C   s   dS )N)     r   r   r   4D:\Karim projects\Glue stance inc\aiform\formauto.pyfavicon#      r   z	/progressc                  C   s   dd } t |  ddS )Nc                   s   s>    t tk rdttt d dV  td t tk sd S d S )Nzdata: )total	processedz

   )processed_urls
total_urlsjsondumpstimesleepr   r   r   r   generate*   s
   
zprogress.<locals>.generateztext/event-stream)mimetype)r   )r    r   r   r   progress(   s   r"   c                 C   s    | t v rt |  |kr| S d S d S N)users)usernamepasswordr   r   r   verify_password1   s   r'   /GETPOST)methodsc                  C   s   t jdkrgt jd } | re| jredadat| }|d  }t j	
dt j	
dt j	
dt j	
dt j	
d	t j	
d
t j	
dt j	
dt j	
dt j	
dt j	
dd}t||}t|ddddS dS tdS )Nr*   filer   ZURLcompany_name	full_namekanaemailphone_numberaddresspostal_code
departmentpositionsite_urlmessage)r-   r.   r/   r0   r1   r2   r3   r4   r5   r6   r7   Tzprocessing_report.csvztext/csv)Zas_attachmentZdownload_namer!   z"No file selected or file is empty.zupload.html)r   methodfilesfilenamer   r   pdZread_csvtolistformgetprocess_urlsr   r   )r,   dfurls	user_inforeportr   r   r   upload_file6   s.   















rD   z/logoutc                   C   s   t tdS )NrD   )r   r   r   r   r   r   logoutV   s   rE   c                 C   s  t | adat }t }t|}|g d | D ]}|g}z|	|}|
  |d t|}|dt | d d}	||g D ]X}
z7|	|
}t|jd}t|}|r}t||}t||
|\}}|r}||
ddtj|dd|d	g d
}	W  qW qE ty } ztd|
 dt|  W Y d }~qEd }~ww |	s|g d W n( tjy } z|dt| d	d	d	d	d	d	d	t|g	 W Y d }~nd }~ww || td7 attt q| d}t|}|d |S )Nr   )zMain URLz
URL AccesszLinks FoundzForm URLzForm Fields FoundzSubmitted Form DatazSubmission VerificationzError DetailsZSuccesszFound z linksFhtml.parser)ensure_asciir   TzError processing URL z: )N/Az Failure - No suitable form foundr   r   r   r   rH   No form submittedz
Failure - r   zutf-8)lenr   r   requestsZSessionr   csvwriterZwriterowr>   raise_for_statusappendget_all_linksr
   textfind_form_fieldsgenerate_form_mappingfind_and_submit_formextendr   r   	ExceptionloggererrorstrZRequestExceptionupdate_progressgetvalueencoder   seek)rA   rB   sessionrC   Z
csv_writerZmain_urlrowresponseZ	all_linksZform_submittedurlsoupfields	form_dataZsubmission_resultZsubmission_verificationeZreport_contentZreport_bytesr   r   r   r?   [   sl   





6

r?   c                 C   sh   g }|  dD ]*}| g dD ] }|jdkr)|dd}|dv r(|t| q|t| qq|S )Nr=   inputZtextareaselectrg   typerQ   )rQ   r0   telcheckboxradioZhidden)find_allnamer>   rO   rY   )rb   rc   r=   elementZ
input_typer   r   r   rR      s   
rR   c           	      C   s   t | j}t| }t|jd}dd |jdddD }g }|D ]}t| |}t |j}||ks8d|v s8d|v r=|| q |S )	NrF   c                 S   s   g | ]}| d qS Zhref)r>   ).0ar   r   r   
<listcomp>   s    z!get_all_links.<locals>.<listcomp>rr   Trp   z	forms.glezdocs.google.com)	r   netlocrK   r>   r
   rQ   rm   r   rO   )	ra   domainr`   rb   linksZ
full_linkslinkZ	full_linkZlink_domainr   r   r   rP      s   




rP   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}t jjddddd|dgdd }t|d! d" d d# }|S )$NaG  
    Given the following form fields and user information, identify the corresponding input names in the form and map them to the provided values. Handle checkboxes, radio buttons, and select fields appropriately. Fill all inputs and select the most appropriate option in checkboxes or radio buttons.
    
    Form Fields:
    u+   
    
    User Information:
    会社名: r-   u   
    名前（姓名）: r.   u   
    ふりがな: r/   u   
    フリガナ: u   
    メールアドレス: r0   u   
    電話番号: r1   u   
    住所: r2   u   
    郵便番号: r3   u   
    部署名: r4   u   
    役職: r5   u   
    サイトURL: r6   u   
    メッセージ: r7   z

    For checkboxes and radio buttons, set the value to "true" for the closest option to the user information, otherwise "false".
    For select fields, choose the most appropriate option based on the user information.
    zgpt-3.5-turbosystemzYou are a sales representative. Please respond with a JSON object mapping form field names to user information values. For checkboxes and radio buttons, use boolean values. For select fields, provide the value of the most appropriate option.)Zrolecontentuseri  )modelmessagesZ
max_tokenschoicesr   ry   )openaiZChatCompletionZcreater   loads)rc   rB   promptr`   Zform_mappingr   r   r   rS      sH   	
	rS   c                    s  |  |}t|jd}|d}td|  |D ]}| d}| dd }|g d}	i }
|	D ]Z}| d}|jd	krH| d
d nd}|r|dksT|dkrd| |dkrc| dd|
|< q4|jdkr|d}|D ]}| d| |kr| d|
|<  q4qp| |d|
|< q4z,t|| td  d|	  d|
  G  fddd}| }t
|}d|fW   S  ty } ztdt|  W Y d }~qd }~ww dS )NrF   r=   zforms founds: actionr8   r>   rf   rn   rg   ri   r   rk   rl   Tvalueonrh   optionzWould submit form to z with method z and payload: c                       s    e Zd Z fddZdd ZdS )z*find_and_submit_form.<locals>.MockResponsec                    s   d| _ d| _ | _d S )N   z7<html><body>Thank you for your submission</body></html>)Zstatus_coderQ   ra   selfZ
submit_urlr   r   __init__  s   
z3find_and_submit_form.<locals>.MockResponse.__init__c                 S   s   d S r#   r   r   r   r   r   rN     s   z;find_and_submit_form.<locals>.MockResponse.raise_for_statusN)__name__
__module____qualname__r   rN   r   r   r   r   MockResponse
  s    r   zForm processing failed: )FrI   )r>   r
   rQ   rm   rW   infolowerrn   r   upperverify_submissionrV   rX   rY   )r^   ra   rd   r`   rb   Zformsr=   Zform_actionZform_methodZform_inputspayloadro   Zelement_nameZelement_typeoptionsr   r   Zsubmit_responseZverification_resultre   r   r   r   rT      sN   






 	rT   c                 C   sx   t | jd}g d}|  }|D ]}||v r d| d  S q|ds(dS tt| jj}d|v s8d|v r:d	S d
S )NrF   )z	thank yousuccess	submittedZreceivedz%Submission likely successful. Found 'z' on the response page.r=   zCForm no longer present on the page. Submission might be successful.r   r   z.URL parameters indicate successful submission.z;Unable to verify submission success. Please check manually.)	r
   rQ   Zget_textr   findr   r   ra   query)r`   rb   Zsuccess_keywordsZ	page_textkeywordZ
url_paramsr   r   r   r     s   
r   c                 C   s   |a | ad S r#   )r   r   )r   r   r   r   r   rZ   3  s   rZ   c                   C      t S r#   )r   r   r   r   r   get_total_urls8  r   r   c                   C   r   r#   )r   r   r   r   r   get_processed_urls<  r   r   __main__T)debug)7flaskr   r   r   r   r   r   r   r   Zflask_httpauthr	   pandasr;   rK   Zbs4r
   urllib.parser   r   r~   rL   r   ior   r   Zloggingr   r   r   ZbasicConfigINFOZ	getLoggerr   rW   appauthZapi_keyr$   Zrouter   r"   r'   Zlogin_requiredrD   rE   r?   rR   rP   rS   rT   r   rZ   r   r   runr   r   r   r   <module>   s\   $



O$5