
    ~h                      j   d dl Z d dlmZ d dlmZ d dl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mZmZ d d	lmZ d d
lmZ dZdZd ZdededdfdZed#dededefd       Zed$d       Zedefd       Z d Z!d Z"dZ#	 	 	 d%dededededz  dedz  dedz  ddfd Z$d$d!Z%e&d"k(  r e%        yy)&    N)BytesIO)sleep)load_dotenv)	webdriver)By)Keys)	CodeAgentWebSearchTooltool)
ActionStep)
load_modelz
I'm trying to find how hard I have to work to get a repo in github.com/trending.
Can you navigate to the profile for the top author of the top trending repo, and give me their total number of commits over the last year?
z
Please navigate to https://en.wikipedia.org/wiki/Chicago and give me a sentence containing the word "1992" that mentions a construction accident.
c                  ~   t        j                  d      } | j                  dt        dt        d       | j                  dt        dd	
       | j                  dt        dd
       | j                  dt        d       | j                  dt        d       | j                  dt        d       | j                         S )Nz;Run a web browser automation script with a specified model.)descriptionprompt?z The prompt to run with the agent)typenargsdefaulthelpz--model-typeLiteLLMModelzfThe model type to use (e.g., OpenAIServerModel, LiteLLMModel, TransformersModel, InferenceClientModel))r   r   r   z
--model-idzgpt-4oz0The model ID to use for the specified model typez
--providerz+The inference provider to use for the model)r   r   z
--api-basez!The API base to use for the modelz	--api-keyz The API key to use for the model)argparseArgumentParseradd_argumentstrsearch_request
parse_args)parsers    Y/opt/mcp/mcp-sentiment/venv/lib/python3.12/site-packages/smolagents/vision_web_browser.pyparse_argumentsr      s    $$1noF
/   u	   ?	   :  
 0  
 /  
     memory_stepagentreturnc                 ,   t        d       t        j                         }| j                  }||j                  j
                  D ]-  }t        |t              s|j                  |dz
  k  s'd |_        / |j                         }t        j                  j                  t        |            }t        d|j                   d       |j!                         g| _        d|j"                   }| j$                  || _        y | j$                  dz   |z   | _        y )Ng      ?   zCaptured a browser screenshot: z pixelszCurrent url: 
)r   helium
get_driverstep_numbermemorysteps
isinstancer   observations_imagesget_screenshot_as_pngPILImageopenr   printsizecopycurrent_urlobservations)r!   r"   drivercurrent_stepprevious_memory_step	png_bytesimageurl_infos           r   save_screenshotr=   B   s   	#J F**L$)LL$6$6 	@ .
;@T@`@`dpstdt@t;?$8	@ 002			wy12/

|7CD+0::<.' v1123H,,4   ;F:R:RUY:Y\d:d  r    text
nth_resultc                 0   t         j                  t        j                  d|  d      }|t	        |      kD  rt        d| dt	        |       d      dt	        |       d|  d}||d	z
     }t         j                  d
|       |d| dt	        |       z  }|S )z
    Searches for text on the current page via Ctrl + F and jumps to the nth occurrence.
    Args:
        text: The text to search for
        nth_result: Which occurrence to jump to (default: 1)
    z//*[contains(text(), 'z')]u	   Match n°z not found (only z matches found)zFound z matches for 'z'.   z"arguments[0].scrollIntoView(true);zFocused on element z of )r7   find_elementsr   XPATHlen	Exceptionexecute_script)r>   r?   elementsresultelems        r   search_item_ctrl_frJ   W   s     ##BHH0FtfC.PQHCM!)J</@X_``c(m_N4&;FJN#D
>E
#J<tCM?CCFMr    c                  ,    t         j                          y)zGoes back to previous page.N)r7   back r    r   go_backrN   i   s     KKMr    c                      t        j                  t              j                  t        j
                        j                          y)z
    Closes any visible modal or pop-up on the page. Use this to dismiss pop-up windows! This does not work on cookie consent banners.
    N)r   ActionChainsr7   	send_keysr   ESCAPEperformrM   r    r   close_popupsrT   o   s*    
 6",,T[[9AACr    c                      t        j                         } | j                  d       | j                  d       | j                  d       | j                  d       t        j                  d|       S )z"Initialize the Selenium WebDriver.z--force-device-scale-factor=1z--window-size=1000,1350z--disable-pdf-viewerz--window-position=0,0F)headlessoptions)r   ChromeOptionsr   r'   start_chrome)chrome_optionss    r   initialize_driverr[   w   s_    ,,.N ?@ 9: 67 78~FFr    c                 `    t        t               t        t        t        g| dgt
        gdd      S )z2Initialize the CodeAgent with the specified model.r'      r%   )toolsmodeladditional_authorized_importsstep_callbacks	max_stepsverbosity_level)r	   r
   rN   rT   rJ   r=   )r_   s    r   initialize_agentrd      s2    7IJ'/j'( r    a(	  
Use your web_search tool when you want to get Google search results.
Then you can use helium to access websites. Don't use helium for Google search, only for navigating websites!
Don't bother about the helium driver, it's already managed.
We've already ran "from helium import *"
Then you can go to pages!
<code>
go_to('github.com/trending')
</code>

You can directly click clickable elements by inputting the text that appears on them.
<code>
click("Top products")
</code>

If it's a link:
<code>
click(Link("Top products"))
</code>

If you try to interact with an element and it's not found, you'll get a LookupError.
In general stop your action after each button click to see what happens on your screenshot.
Never try to login in a page.

To scroll up or down, use scroll_down or scroll_up with as an argument the number of pixels to scroll from.
<code>
scroll_down(num_pixels=1200) # This will scroll one viewport down
</code>

When you have pop-ups with a cross icon to close, don't try to click the close icon by finding its element or targeting an 'X' element (this most often fails).
Just use your built-in tool `close_popups` to close them:
<code>
close_popups()
</code>

You can use .exists() to check for the existence of an element. For example:
<code>
if Text('Accept cookies?').exists():
    click('I accept')
</code>

Proceed in several steps rather than trying to solve the task in one shot.
And at the end, only when you have your answer, return your final answer.
<code>
final_answer("YOUR_ANSWER_HERE")
</code>

If pages seem stuck on loading, you might have to wait, for instance `import time` and run `time.sleep(5.0)`. But don't overuse this!
To list elements on page, DO NOT try code-based element searches like 'contributors = find_all(S("ol > li"))': just look at the latest screenshot you have and read it visually, or use your tool search_item_ctrl_f.
Of course, you can act on buttons like a user would do when navigating.
After each code blob you write, you will be automatically provided with an updated screenshot of the browser and the current browser url.
But beware that the screenshot will only be taken at the end of the whole action, it won't see intermediate states.
Don't kill the browser.
When you have modals or cookie banners on screen, you should get rid of them before you can click anything else.
r   
model_typemodel_idproviderapi_baseapi_keyc                     t                t        |||||      }t               at	        |      }|j                  d       |j                  | t        z          y )N)rg   rh   ri   zfrom helium import *)r   r   r[   r7   rd   python_executorrunhelium_instructions)r   re   rf   rg   rh   ri   r_   r"   s           r   run_webagentrn      sU     M z8h[bcE  FU#E 
01	IIf**+r    c                      t               } t        | j                  | j                  | j                  | j
                  | j                  | j                         y )N)r   rn   r   re   rf   rg   rh   ri   )argss    r   mainrq      s7    Ddoot}}dmmT]]\`\h\hir    __main__)rA   )r#   N)NNN)'r   ior   timer   r'   	PIL.Imager/   dotenvr   seleniumr   selenium.webdriver.common.byr   selenium.webdriver.common.keysr   
smolagentsr	   r
   r   smolagents.agentsr   smolagents.clir   github_requestr   r   r=   r   intrJ   rN   rT   r[   rd   rm   rn   rq   __name__rM   r    r   <module>r      sA          + / 5 5 ( %

$N I $ * S c #  "  
 Dc D DG	6 z  ,,, , Dj	,
 Dj, 4Z, 
,.j zF r    