
    FEibS                        U d Z ddlZddlZddlZddlmZmZmZmZm	Z	m
Z
mZmZmZ ddlmZ er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 dd
lmZmZm Z m!Z! ddl"m"Z" ddl#m$Z$m%Z% ddl&m'Z'm(Z(m)Z) ed   Z*ed   Z+i 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&Z,ee-e-f   e.d'<   d(d)d*d+d,Z/ee-e0f   e.d-<   g dZ1e
e-   e.d.<   dDd/eg ef   d0e0d1efd2Z2d3e-d1e-fd4Z3d5e0d1e0fd6Z4d7e-d1e-fd8Z5d9e-d:e*d;e-d1ee-d<f   fd=Z6	 	 	 	 	 	 	 	 dEd3e-d5e0d7e-d>e7d?e-d@e7d;ee-   d:e*d1ee-d<df   fdAZ8dFdBZ9e:dCk(  r e9        yy)Ga  
Configurable Google Trends CSV Downloader
Download trends with custom filters: location, time period, category, sort, etc.

Usage Examples:
    # Download US trends from past 24 hours
    py download_trends_configurable.py

    # Download Canada trends from past 4 hours, Sports only
    py download_trends_configurable.py --geo CA --hours 4 --category sports

    # Download UK trends from past 7 days, sorted by search volume
    py download_trends_configurable.py --geo UK --hours 168 --sort volume
    N)	OptionalCallableAnyDictSetListLiteralUnionTYPE_CHECKING)	webdriver)By)Keys)WebDriverWait)expected_conditions)Options)TimeoutExceptionNoSuchElementExceptionWebDriverException ElementClickInterceptedException)datetime   )	COUNTRIES	US_STATES)InvalidParameterErrorBrowserErrorDownloadError)csvjsonparquet	dataframe)	relevancetitlevolumerecencyall autosbeautybusinessclimateentertainmentfoodgameshealthhobbiesjobslawotherpetspoliticsscienceshoppingsportstechtravel)r7   
technologyr9   
CATEGORIES      0      )4h24h48h7dTIME_PERIODSSORT_OPTIONSdownload_funcmax_retriesreturnc                 \   t        |      D ]  }	  |        c S  y# t        t        t        f$ r|}||dz
  k  rZd|z  }t	        d|dz    dt        |      j                          t	        d| d|dz    d| d       t        j                  |       nt	        d	| d
        Y d}~d}~ww xY w)a  Wrapper to retry download with exponential backoff.

    Args:
        download_func: Function to call for download
        max_retries: Maximum number of retry attempts

    Returns:
        Result of download_func

    Raises:
        Last exception if all retries fail
    r      z[WARN] Attempt z	 failed: z[INFO] Retrying in zs... (/)z[ERROR] All z attempts failedN)	ranger   r   r   printtype__name__timesleep)rF   rG   attempte	wait_times        `/home/sietch6/trending-topics-pipeline/venv/lib/python3.12/site-packages/trendspyg/downloader.py_download_with_retryrW   W   s     % 	 ?" m-=> 		q(L	!}Id1g>N>N=OPQ+I;fWq[M;-WXYZ

9% [M1ABC	 &		s   B+A2B&&B+geoc                    | j                         } | t        v s| t        v r| S t        t        j                               t        t        j                               z   D cg c]&  }t        |       dkD  r|j                  | d         r|( c}dd }d|  d}|r|ddj                  |       dz  }|d	t        t               d
z  }|dt        t               dz  }|dz  }t        |      c c}w )zValidate geo parameter against available countries and US states.

    Args:
        geo: Country or US state code

    Raises:
        InvalidParameterError: If geo code is invalid

    Returns:
        Validated geo code (uppercased)
    r   N   zInvalid geo code ''. Did you mean one of: , ?z

Available: z% countries (US, CA, UK, DE, FR, ...) zor z  US states (CA, NY, TX, FL, ...)zN

See trendspyg.config.COUNTRIES and trendspyg.config.US_STATES for full list.)	upperr   r   listkeyslen
startswithjoinr   )rX   codesimilar	error_msgs       rV   validate_georh   s   s     ))+C
i3)+
 !%Y^^%5 6inn>N9O O <c(Q,4??3q6#:  <<>Q@G %SE,I-dii.@-ACC	?3y>"22WXXI3s9~&&FGGIccI
	
**<s    +C-hoursc                 :    g d}| |v r| S t        d|  d| d      )zValidate hours parameter against available time periods.

    Args:
        hours: Time period in hours

    Raises:
        InvalidParameterError: If hours value is invalid

    Returns:
        Validated hours value
    r<   r=   r>   r?   zInvalid hours value 'z'. Must be one of: zr
  4   = Past 4 hours
  24  = Past 24 hours (1 day)
  48  = Past 48 hours (2 days)
  168 = Past 168 hours (7 days))r   )ri   valid_hourss     rV   validate_hoursrm      s<     #K

w&9+ G* 	+     categoryc                    | j                         } | t        v r| S t        j                         D cg c](  }|j                  | dd       st	        |       dk\  s'|* c}dd }d|  d}|r|ddj                  |       dz  }|d	dj                  t        t        j                                      z  }t        |      c c}w )
zValidate category parameter against available categories.

    Args:
        category: Category name

    Raises:
        InvalidParameterError: If category is invalid

    Returns:
        Validated category (lowercased)
    N   rZ   zInvalid category 'r[   r\   r]   r^   z

Available categories: )lowerr;   ra   rc   rb   rd   sortedr   )ro   catrf   rg   s       rV   validate_categoryru      s     ~~H: )oo/fs3>>(2A,3OSVW_S`deSesfgihijG$XJb1I-dii.@-ACC	-diiz?P8Q.R-STTI
	
** gs   CCCcsv_pathoutput_formatdownload_dirzpd.DataFramec                 .   |dk(  r| S 	 ddl }	  |j                  |       }|dk(  r|S | j                  dd	      d   }|d
k(  r\|dz   }	 |j                  |dd       t        j                  |        t        dt        j                  j                  |              |S |dk(  r[|dz   }	 |j                  |d       t        j                  |        t        dt        j                  j                  |              |S t        d|       # t        $ r t        d| d      w xY w# t        $ r}t	        d|       d}~ww xY w# t        $ r}t	        d|       d}~ww xY w# t        $ r t        d      t        $ r}t	        d|       d}~ww xY w)a  Convert downloaded CSV to requested output format.

    Args:
        csv_path: Path to the downloaded CSV file
        output_format: Desired output format
        download_dir: Directory for output files

    Returns:
        Path to converted file or DataFrame object

    Raises:
        ImportError: If required library is not installed
        DownloadError: If conversion fails
    r   r   Nzpandas is required for 'z7' format.
Install with: pip install trendspyg[analysis]zFailed to read CSV file: r    .r   r   z.jsonrecordsrJ   )orientindentz[OK] Converted to JSON: zFailed to convert to JSON: r   z.parquetF)indexz[OK] Converted to Parquet: zIpyarrow is required for parquet format.
Install with: pip install pyarrowzFailed to convert to Parquet: zUnsupported output format: )pandasImportErrorread_csv	Exceptionr   rsplitto_jsonosremoverN   pathbasename
to_parquetr   )	rv   rw   rx   pddfrT   	base_path	json_pathparquet_paths	            rV   _convert_csv_to_formatr      s   & 
=R[["
 #	 Q'*I'		CJJy1J=IIh,RWW-=-=i-H,IJK 
)	# :-	FMM,eM4IIh/0@0@0N/OPQ  "=m_ M
NN_  
&}o 6< <
 	

  =7s;<<=$  	C"=aS ABB	C  	4   	F"@ DEE	FsT   D D' AE (AE% D$'	E0D>>E	E"EE"%FFFactive_onlysort_byheadlessc           	         t        |       } t        |      }t        |      }|2t        j                  j                  t        j                         d      }t        j                  j                  |      }t        j                  |d       t        d t        j                  |      D              }t               }	|dddd}
|	j                  d|
       |rD|	j                  d	       |	j                  d
       |	j                  d       |	j                  d       |	j                  d       |	j                  ddg       t        d       t        d|         t        d| d       t        d|        t        d|        t        d|        	 t        j                   |	      }	 d|  }|dk7  r|d| z  }t&        j)                  |j+                         d      }|r|d| z  }t        d|        |j)                  |       t-        |d       j/                  t1        j2                  t4        j6                  d!f             |r&	 t        d"       t-        |d#      j/                  t1        j8                  t4        j:                  d$f            }|j=                          t?        j@                  d%       t-        |d&      j/                  t1        j8                  t4        j:                  d'f            }|jC                  d(|       t?        j@                  d)       |jE                  t4        jF                  d*      jI                  tJ        jL                         t?        j@                  d)       |j+                         d-k7  rt        d.| d/       t        d0       t-        |d       j/                  t1        j8                  t4        j6                  d!f            }|j=                          t?        j@                  d)       t-        |d#      j/                  t1        j2                  t4        j:                  d1f            }|jC                  d(|       t        d2       d }d%}d3}t               }||k  r]t?        j@                  |       ||z  }t        d4 t        j                  |      D              }||z
  }|rt        d5|d6d7       n||k  r]|s*t        d8 t        j                  |      D              }||z
  }|rtS        |      d9   }t        j                  j                  ||      }tU        jV                         jY                  d:      }d;|  d<| d=| d<| d>	}t        j                  j                  ||      }t        jZ                  ||       t        d?|        t        d@|        t]        |||      }|dAk(  rt        dBt_        |       dC       ||ja                          S tc        dD|       # t"        $ r}t%        d| d      d}~ww xY w# tN        tP        f$ r!}t        d+       t        d,       Y d}~d}~ww xY w# tN        $ r}t%        dE| dF      d}~wtP        $ r}t%        dG| dH      d}~wtd        $ r}t%        dI| dJ      d}~wtf        t$        tb        f$ r  th        $ r*}t%        dKtk        |      jl                   dL| dM      d}~ww xY w# |ja                          w xY w)NaK  
    Download Google Trends data with configurable filters and output formats

    Args:
        geo: Country code (US, CA, UK, IN, JP, etc.)
        hours: Time period in hours (4, 24, 48, 168)
        category: Category filter (all, sports, entertainment, etc.)
        active_only: Show only active trends
        sort_by: Sort criteria (relevance, title, volume, recency)
        headless: Run browser in headless mode
        download_dir: Directory to save file
        output_format: Output format (csv, json, parquet, dataframe)

    Returns:
        Path to downloaded file (for csv/json/parquet) or DataFrame (for dataframe format),
        or None if failed

    Raises:
        InvalidParameterError: If any parameters are invalid
        BrowserError: If browser automation fails
        DownloadError: If file download fails
    N	downloadsT)exist_okc              3   D   K   | ]  }|j                  d       s|  yw.csvNendswith.0fs     rV   	<genexpr>z-download_google_trends_csv.<locals>.<genexpr>@  s     Sq

6@RS     F)zdownload.default_directoryzdownload.prompt_for_downloadzdownload.directory_upgradezsafebrowsing.enabledprefsz--headless=newz--disable-gpuz--no-sandboxz--disable-dev-shm-usagez--log-level=3excludeSwitcheszenable-loggingz[INFO] Opening Google Trends...z       Location: z       Time: Past z hoursz       Category: z       Active only: z       Sort: )optionsz Failed to start Chrome browser: z

Please ensure:
1. Chrome browser is installed
2. ChromeDriver is compatible with your Chrome version
3. You have proper permissions

ChromeDriver is auto-downloaded by Selenium, but you need Chrome browser installed.z'https://trends.google.com/trending?geo=r=   z&hours=r&   z&cat=z[INFO] Navigating to: 
   z//button[contains(., 'Export')]z.[INFO] Enabling 'Active trends only' filter...rZ   z)button[aria-label*='select trend status']g      ?rq   z;button[role='switch'][aria-label='Show active trends only']zarguments[0].click();r   bodyzF[WARN] Could not toggle 'Active trends only' filter - using all trendszM       Reason: UI element not found (Google may have changed their interface)r!   z[INFO] Note: Sort by 'z:' only affects UI display (CSV exports in relevance order)z[INFO] Downloading CSV...zli[data-action="csv"]z#[INFO] Waiting for file download...g        c              3   D   K   | ]  }|j                  d       s|  ywr   r   r   s     rV   r   z-download_google_trends_csv.<locals>.<genexpr>       ZaqzzRXGYZr   z[INFO] File detected after z.1fsc              3   D   K   | ]  }|j                  d       s|  ywr   r   r   s     rV   r   z-download_google_trends_csv.<locals>.<genexpr>  r   r   r   z%Y%m%d-%H%M%Strends__h_r   z[OK] Downloaded: z[OK] Location: r    z![OK] Converted to DataFrame with z rowszNo new file detected after download attempt.

Possible causes:
- Download may have failed silently
- File may have been downloaded to a different location
- Network timeout during download

Expected download directory: zPage load timeout: z

Possible causes:
- Slow internet connection
- Google Trends website is down or slow
- Network firewall blocking access

Try again with a better connection or check https://trends.google.com/trendingzCould not find UI element: a  

Possible causes:
- Google Trends changed their website design
- Page did not load correctly

Solutions:
- Update trendspyg: pip install --upgrade trendspyg
- Check GitHub issues: https://github.com/flack0x/trendspyg/issues
- Report this issue if it persistszCould not click UI element: zq

An element is blocking the click. This may be temporary.
Try running again - this often resolves automatically.z"Unexpected error during download: z: z_

This is an unexpected error. Please report it at:
https://github.com/flack0x/trendspyg/issues)7rh   rm   ru   r   r   rd   getcwdabspathmakedirssetlistdirr   add_experimental_optionadd_argumentrN   r   Chromer   r   r;   getrr   r   untilECpresence_of_element_locatedr   XPATHelement_to_be_clickableCSS_SELECTORclickrQ   rR   execute_scriptfind_elementTAG_NAME	send_keysr   ESCAPEr   r   r`   r   nowstrftimerenamer   rb   quitr   r   r   r   rO   rP   )rX   ri   ro   r   r   r   rx   rw   existing_fileschrome_optionsr   driverrT   urlcat_codeactive_buttontoggleexport_buttondownload_csvmax_wait_timecheck_intervalelapsed_time	new_filescurrent_filesdownloaded_file	full_path	timestampnew_namenew_pathresults                                 rV   download_google_trends_csvr     s   B s
C5!E *H ww||BIIK=77??<0LKKt, SBJJ|$<SSN YN&2(-&* $	E **7E:##$45##O4##N3##$=> 0**+<?O>PQ	+-	cU
#$	ugV
,-	hZ
()	 
./	M'
#$

!!.9f7u= B;WUG$$C >>(.."2B7U8*%%C&se,-

3 	fb!''**BHH6W+XY	
 hFG -fa 8 > >..Al/mn! ##%

3 'vq177..A~/  A %%&=vF

1 ##BKK8BB4;;O

1 ==?k)*7)3mno 	)*%fb177&&2S'TU
 	

1 %VQ/55**BOO=T+UV
 	5|D 	34!e	]*JJ~&N*L  Z2::l+CZZM%6I3L3EQGH ]* Z2::l+CZZM%6I"9oa0O\?CI !//@I QugRz9+TJHww||L(;HIIi*%hZ01OH:./ ,Hm\RF +9#f+eLMj 	g  0
 1=~? {  
.qc 2b b
 	

l %&<= h^`eggh`  
!! %] ]
 	
 " 

)! -1 1	
 		
 , 
*1# .E E
 	
 "<?  
0a1A1A0B"QC H: :
 	

 	s   W5 (B Y 	D%X .EY DY 'Y 5	X>XXY$Y :Y  YY 	[ Y  [ ,Y;;[ Z [ 6%[[  [# #[5c            	         t        j                  dt         j                  d      } | j                  dt        dd       | j                  dt
        g d	d
d       | j                  dt        t        t        j                               dd       | j                  ddd       | j                  dt        t        dd       | j                  ddd       | j                  dt        d       | j                         }t        d       t        d       t        d       t        |j                  j                         |j                  |j                   |j"                  |j$                  |j&                   |j(                        }t        d       |rFt*        j,                  j/                  |      }t        d|d d!       t        d"       t1        d#       y t        d$       t1        d%       y )&Nz/Download Google Trends data with custom filtersa  
Examples:
  # Default (US, past 24 hours, all categories)
  %(prog)s

  # Canada, past 4 hours
  %(prog)s --geo CA --hours 4

  # UK, past 7 days, Sports only, sorted by volume
  %(prog)s --geo UK --hours 168 --category sports --sort volume

  # India, active trends only
  %(prog)s --geo IN --active-only

  # Japan, Entertainment category, sorted by recency
  %(prog)s --geo JP --category entertainment --sort recency

Available countries (geo codes):
  US, CA, UK, AU, IN, JP, DE, FR, BR, MX, ES, IT, RU, KR, and many more

Available categories:
  all, sports, entertainment, business, politics, technology, health,
  science, games, shopping, food, travel, beauty, hobbies, climate, etc.
        )descriptionformatter_classepilogz--geoUSz4Country code (US, CA, UK, IN, JP, etc.). Default: US)rO   defaulthelpz--hoursrk   r=   z>Time period: 4 (4h), 24 (24h), 48 (48h), 168 (7d). Default: 24)rO   choicesr   r   z
--categoryr%   zCategory filter. Default: allz--active-only
store_truezShow only active trends)actionr   z--sortr!   z>Sort by: relevance, title, volume, recency. Default: relevancez	--visiblez*Run browser in visible mode (not headless)z--output-dirz$Output directory for downloaded file)rO   r   zF======================================================================z%Google Trends Configurable Downloader)rX   ri   ro   r   r   r   rx   zFile size: ,z bytesz
Done!r   z
Failed to downloadr   )argparseArgumentParserRawDescriptionHelpFormatterr   strintr`   r;   ra   rE   
parse_argsrN   r   rX   r_   ri   ro   r   sortvisible
output_dirr   r   getsizeexit)parserargsfilepathsizes       rV   mainr     s   $$E <<F: c4R  T 	5Er\  ^ 3Z__=N8OY^;  = 5  7 sL+\  ^ LH  J SB  D D	&M	
12	&M)HHNNjj$$		\\!__H 
&Mwwx(D86*+iQ$%Qrn   __main__)rq   )r   r=   r%   Fr!   TNr   )rH   N);__doc__r   rQ   r   typingr   r   r   r   r   r   r	   r
   r   seleniumr   r   r   selenium.webdriver.common.byr   selenium.webdriver.common.keysr   selenium.webdriver.support.uir   selenium.webdriver.supportr   r   !selenium.webdriver.chrome.optionsr   selenium.common.exceptionsr   r   r   r   r   configr   r   
exceptionsr   r   r   OutputFormat
SortOptionr;   r   __annotations__rD   r   rE   rW   rh   rm   ru   r   boolr   r   rP    rn   rV   <module>r     s   
   Z Z Z  + / 7 @ 5   )  <=>?
	2W h 
	
 y _ F W h y F 
5 W F 
  y!" 
#$ )
DcN 2 
	 d38n  Fd3i ES(9  TW 8+c +c +># # 4+ + +8HOHOHO HO 3	HOX "&"'}	}} } 	}
 } } 3-}  } 3$%}@L^ zF rn   