
    FEi                     j   d Z ddlZddlZddlmc mZ ddlmZ ddlm	Z	m
Z
mZmZmZmZmZ erddlZddlZddlmZmZmZ ddlmZmZmZ ddlmZ ed	   Zd
ededede def
dZ!de d
ededdfdZ"de#d
ededede de
e	   fdZ$de
e	   dedededee
e	   edf   f
dZ%d
edefdZ&edddddfd
edededede dedee
e	   edf   fdZ'eddddddfd
edededede ded    dedee
e	   edf   fd!Z(	 	 	 	 	 d(d"e
e   dedede d#ed$e)de	ee
e	   f   fd%Z*	 	 	 	 	 d)d"e
e   dedede d#ed&e de	ee
e	   f   fd'Z+y)*a/  
Google Trends RSS Feed Downloader - Fast, Rich Media Data

This module provides fast access to Google Trends RSS feed data,
including images, news articles, and headlines. Perfect for:
- Real-time monitoring
- Qualitative research (news context)
- Visual content (images for presentations)
- Fast data collection (0.2s vs 10s for CSV)

Use Cases:
- Journalism: Breaking news validation with sources
- Research: Mixed methods (combine with CSV for complete picture)
- Trading: Fast alerts with news context
- Marketing: Quick trend checks with visual content
    N)datetime)DictListOptionalUnionLiteralTYPE_CHECKINGcast   )	COUNTRIES	US_STATESDEFAULT_GEO)InvalidParameterErrorDownloadErrorRateLimitError)get_rss_cache)csvjson	dataframedictgeoinclude_imagesinclude_articlesmax_articles_per_trendreturnc                     |  d| d| d| S )z-Generate a cache key from request parameters.: )r   r   r   r   s       d/home/sietch6/trending-topics-pipeline/venv/lib/python3.12/site-packages/trendspyg/rss_downloader.py_make_cache_keyr    %   s&     U!N#1%5$6a8N7OPP    status_codeurlc           	          | dk(  s| dk(  rt        d|  d| d|       | dk(  rt        d| d|       | d	k\  rt        d
|  d|       t        d|  d| d| d      )z
    Raise appropriate exception based on HTTP status code.

    Provides specific, actionable error messages for common HTTP errors.
    i  i  zRate limit exceeded (HTTP u  )

Google is temporarily blocking requests. Solutions:
• Wait 1-2 minutes before trying again
• Reduce request frequency (add delays between calls)
• Use caching: results are cached for 5 minutes by default
• For batch operations, use max_concurrent=5 or delay=0.5

Geo: z | URL: i  z-RSS feed not found (HTTP 404)

The geo code 'zt' may not have an RSS feed available.
Try a different country code or check if the code is correct.

URL attempted: i  z!Google Trends server error (HTTP u   )

Google's servers are having issues. This is temporary.
• Wait a few minutes and try again
• Check https://trends.google.com to verify it's working

URL: zHTTP error z when fetching RSS feed

Geo: 
URL: zQ

If this persists, please report at:
https://github.com/flack0x/trendspyg/issues)r   r   )r"   r   r#   s      r   _handle_http_errorr&   /   s     c[C/( 6 5'
 	
 
	 E "!U$
 	
 
	/} = 5	
 	
 + '5 5 ::
 	
r!   xml_contentc           	      .   	 t        j                  |       }ddi}g }|j	                  d      D ]  }	|	j                  d      }
|
|
j                  nd}|	j                  d|      }||j                  nd}|	j                  d	      }||j                  nd}d}|r	 t        j                  |d
      }|||d| d| dd}|rH|	j                  d|      }|	j                  d|      }||j                  nd||j                  ndd|d<   |rg }|	j	                  d|      d| }|D ]  }|j                  d|      }|j                  d|      }|j                  d|      }|j                  d|      }||j                  nd||j                  nd||j                  nd||j                  ndd}|j                  |        ||d<   |j                  |        |S # t         j                  $ r}t        d|       d}~ww xY w# t        $ r |}Y bw xY w)a   
    Parse RSS XML content into list of trend dictionaries.

    Shared parsing logic used by both sync and async downloaders.

    Args:
        xml_content: Raw XML bytes from RSS feed
        geo: Geographic code for explore links
        include_images: Include image URLs and sources
        include_articles: Include news articles data
        max_articles_per_trend: Max news articles per trend

    Returns:
        List of trend dictionaries

    Raises:
        DownloadError: If XML parsing fails
    zFailed to parse RSS XML: Nhtz&https://trends.google.com/trending/rssz.//itemtitlezN/Azht:approx_trafficpubDatez%a, %d %b %Y %H:%M:%S %zz+https://trends.google.com/trends/explore?q=z&geo=z	&hl=en-UStrendtraffic	publishedexplore_linkz
ht:picturezht:picture_source)r#   sourceimagezht:news_itemzht:news_item_titlezht:news_item_urlzht:news_item_sourcezht:news_item_picture)headliner#   r1   r2   news_articles)ET
fromstring
ParseErrorr   findallfindtextr   strptime
ValueErrorappend)r'   r   r   r   r   rootenstrendsitemr*   r-   traffic_elemr.   pub_date_elempub_date_strr/   
trend_datapicture_elempicture_source_elemarticles
news_itemsnewsheadline_elemurl_elemsource_elem
image_elemarticles                               r   _parse_rss_xmlrQ   X   sn   2=}}[)
 8	9B FY' <"		'"#/

Uyy!4b9'3'?,##U		),-:-F}))D 15	)$--l<VW	 "I%PUVYUZZcd	

 99\26L"&)),?"D -9,D|(($6I6U-22[_#Jw Hnb9:Q;QRJ" ) $		*> C99%7<"ii(=rB!YY'=rB
 7D6O 2 2UY,4,@8==d2=2Ik..t0:0FZ__D	 () +3J'j!y<"| MO == =7s;<<=4  )(	)s)   G HH/G==HHHrA   output_formatzpd.DataFramec                    |dk(  r| S |dk(  r	 ddl }g }| D ]  }|d   |d   |d   |d	   d
}|rd|v r|d   d   |d<   |d   d   |d<   |rDd|v r@t        |d         |d<   |d   r*|d   d   d   |d<   |d   d   d   |d<   |d   d   d   |d<   |j                  |         |j                  |      S |dk(  rvddl}g }	| D ]X  }|j                         }
t        |
j                  d      t              r|
d   j                         |
d<   |	j                  |
       Z |j                  |	d      S |dk(  r(ddl}ddlm}  |       }| syg d
}|r|j                  ddg       |r|j                  g d       |j!                  ||      }|j#                          | D ]  }|d   |d   t        |d   t              r|d   j                         n|d   |d	   d
}|rd|v r|d   d   |d<   |d   d   |d<   |rDd|v r@t        |d         |d<   |d   r*|d   d   d   |d<   |d   d   d   |d<   |d   d   d   |d<   |j%                  |        |j'                         S t)        d| d      # t        $ r t        d      w xY w) a5  
    Format trends data into requested output format.

    Shared formatting logic used by both sync and async downloaders.

    Args:
        trends: List of trend dictionaries
        output_format: Output format ('dict', 'dataframe', 'json', 'csv')
        include_images: Whether images were included
        include_articles: Whether articles were included

    Returns:
        Formatted output in requested format

    Raises:
        InvalidParameterError: If output_format is invalid
        ImportError: If pandas not installed for 'dataframe' format
    r   r   r   NzXpandas is required for 'dataframe' format.
Install with: pip install trendspyg[analysis]r-   r.   r/   r0   r,   r2   r#   	image_urlr1   image_sourcer4   article_countr3   top_article_headlinetop_article_urltop_article_sourcer      )indentr   )StringIO )rV   rW   rX   rY   )
fieldnameszInvalid output_format: 'z5'. Must be one of: 'dict', 'dataframe', 'json', 'csv')pandasImportErrorlenr=   	DataFramer   copy
isinstancegetr   	isoformatdumpsr   ior\   extend
DictWriterwriteheaderwriterowgetvaluer   )rA   rR   r   r   pd	flattenedr-   flatr   json_trends
trend_copyr   r\   outputr^   writerrows                    r   _format_outputrv      sd   0 	+	%	 	 	#Ew +";/ %n 5	D 'U"2$)'N5$9[!',W~h'?^$Ou$<(+E/,B(C_%)383I!3LZ3XD/0.3O.DQ.G.ND*+161G1J81TD-.T")	#, r||I&&	&	  	+EJ*..5x@*4[*A*K*K*M
;'z*		+ zz+az00	%	 G
{N;<pq:> 	!Ew +?I%P[J\^f?gU;/99;mrs~m %n 5	C 'U"2#(>%#8K &+GnX&>N#Ou$<'*5+A'BO$)272H2KJ2WC./-2?-CA-Fu-MC)*05o0Fq0I(0SC,-OOC '	!*    $&}o 6A A
 	
o  	@ 	s   I+ +J c                    | j                         } | t        v s| t        v r| S t        t        j                               t        t        j                               z   D cg c]&  }|j                  | d         rt        |       dkD  r|( c}dd }d|  d}|r|ddj                  |       dz  }|d	t        t               d
t        t               dz  }|dz  }t        |      c c}w )zValidate geo parameter for RSS.

    Args:
        geo: Country code (e.g., 'US', 'GB')

    Returns:
        Validated geo code (uppercase)

    Raises:
        InvalidParameterError: If geo is invalid
    r   N   zInvalid geo code 'z'.z Did you mean: z, ?z

Available: z countries, z
 US statesz>
See trendspyg.config.COUNTRIES and trendspyg.config.US_STATES)	upperr   r   listkeys
startswithra   joinr   )r   codesimilar	error_msgs       r   _validate_geo_rssr   8  s     ))+C
i3)+
 !%Y^^%5 6inn>N9O O ;//#a&)SX\  ;;=A?G %SE,Ityy'9&:!<<	?3y>"2,s9~>NjYYIRRI
	
**;s    +C'r   Trx   cachec           	         t        |       } t        | |||      }|r)t               j                  |      }|t	        ||||      S d|  }	 t        j                  |d      }	|	j                          t#        	j$                  | |||
      }|rt               j'                  ||       t	        ||||      S # t
        j                  $ r+}
t        |
j                  j                  | |       Y d}
~
}d}
~
wt
        j                  $ r t        d      t
        j                  $ r t        d      t
        j                  $ r,}
t        dt        |
      j                    d|
 d	|       d}
~
ww xY w)u6  
    Download Google Trends RSS feed data with rich media content.

    **Fast alternative to CSV download** (0.2s vs 10s):
    - Returns ~10-20 current trending topics
    - Includes images, news articles, headlines
    - No time filtering (always current trends)
    - Perfect for real-time monitoring and qualitative research

    **Caching:** Results are cached for 5 minutes by default to reduce
    API calls and improve performance for repeated requests. Use `cache=False`
    to bypass the cache and always fetch fresh data.

    **Data Provided (RSS-specific):**
    - ✅ News article headlines and URLs
    - ✅ Article images and sources
    - ✅ Trend image (thumbnail)
    - ✅ Publication timestamp
    - ✅ Traffic volume

    **NOT Provided (use CSV for these):**
    - ❌ Start/end timestamps
    - ❌ Related search breakdown
    - ❌ Time period filtering
    - ❌ Category filtering
    - ❌ Large dataset (480 trends)

    **When to use RSS:**
    - Journalism: Need news articles + sources quickly
    - Research: Qualitative analysis (article content)
    - Monitoring: Real-time alerts (fast, frequent polling)
    - Visual content: Images for presentations/articles

    **When to use CSV instead:**
    - Need >20 trends (CSV has 480)
    - Need time filtering (4h, 24h, 48h, 7d)
    - Need category filtering (sports, tech, etc.)
    - Need historical context (start/end times)
    - Statistical analysis (large dataset)

    Args:
        geo: Country/region code (e.g., 'US', 'GB', 'US-CA')
              Supports 125 countries + 51 US states
        output_format: Output format
            - 'dict' (default): List of dictionaries (Python native)
            - 'dataframe': pandas DataFrame (requires pandas)
            - 'json': JSON string
            - 'csv': CSV string
        include_images: Include image URLs and sources
        include_articles: Include news articles data
        max_articles_per_trend: Max news articles to include per trend (default: 5)
        cache: Use cached results if available (default: True)
               Set to False to always fetch fresh data

    Returns:
        Depending on output_format:
        - 'dict': List[Dict] - List of trend dictionaries
        - 'dataframe': pd.DataFrame - pandas DataFrame
        - 'json': str - JSON string
        - 'csv': str - CSV string

    Raises:
        InvalidParameterError: If parameters are invalid
        DownloadError: If RSS fetch fails

    Examples:
        >>> # Basic usage - Fast data for monitoring
        >>> trends = download_google_trends_rss(geo='US')
        >>> print(f"Found {len(trends)} trending topics")
        >>> print(trends[0]['trend'])  # First trend title

        >>> # For research - Get news articles for qualitative analysis
        >>> trends = download_google_trends_rss(
        ...     geo='US',
        ...     output_format='dataframe',  # pandas for analysis
        ...     include_articles=True
        ... )
        >>> # Access news articles for each trend
        >>> for trend in trends:
        ...     print(f"{trend['trend']}: {len(trend['news_articles'])} articles")

        >>> # For journalism - Quick check with sources
        >>> trends = download_google_trends_rss(geo='US', output_format='json')
        >>> # Use in API or save to file

        >>> # For presentations - Get images
        >>> trends = download_google_trends_rss(geo='US', include_images=True)
        >>> image_url = trends[0]['image']['url']
        >>> image_source = trends[0]['image']['source']

        >>> # Bypass cache for fresh data
        >>> trends = download_google_trends_rss(geo='US', cache=False)

    Performance:
        - Speed: ~0.2 seconds (50x faster than CSV), instant if cached
        - Trends: ~10-20 items
        - Data size: ~50-100KB
        - Update frequency: ~9 times per hour
        - Cache TTL: 5 minutes (configurable via set_rss_cache_ttl)

    Data Structure (dict format):
        {
            'trend': str,              # Search term
            'traffic': str,            # '200+', '2000+', etc.
            'published': datetime,     # Publication time
            'image': {                 # Trend thumbnail (if include_images=True)
                'url': str,
                'source': str
            },
            'news_articles': [         # Related articles (if include_articles=True)
                {
                    'headline': str,
                    'url': str,
                    'source': str,
                    'image': str
                }
            ],
            'explore_link': str        # Google Trends explore URL
        }
    N+https://trends.google.com/trending/rss?geo=
   timeout   Connection failed - cannot reach Google Trends

Possible causes:
• No internet connection
• DNS resolution failed
• Firewall blocking the request

Check your internet connection and try again.   Request timed out after 10 seconds

Possible causes:
• Slow internet connection
• Google Trends is experiencing delays

Try again in a moment.Network error: 

Details: r%   r'   r   r   r   r   )r   r    r   re   rv   requestsraise_for_status	HTTPErrorr&   responser"   ConnectionErrorr   TimeoutRequestExceptiontype__name__rQ   contentset)r   rR   r   r   r   r   	cache_keycached_trendsr#   r   r?   rA   s               r   download_google_trends_rssr   V  s   B C
 C  ^5EG]^I%++I6$!-P`aa 8u
=C!
<<R0!!#B $$%)5F Iv. &-AQRRY  =1::113<<## 
<
 	
  
%
 	
 $$ 
d1g../ 0s 5
 	

s%   'B6 6E+	!C//AE+?'E&&E+sessionaiohttp.ClientSessionc           	      t  K   	 ddl }t        |       } t        | |||      }|r)t	               j                  |      }	|	t        |	|||      S d|  }
|du }	 | |j                         }	 |j                  |
 |j                  d            4 d{   }|j                  dk7  rt        |j                  | |
       |j                          d{   }ddd      d{    |r||j)                          d{    	 t+        | |||      }|rt	               j-                  ||       t        ||||      S # t        $ r t        d      w xY w7 7 7 w# 1 d{  7  sw Y   xY w# |j                  $ r!}t        |j                  | |
       Y d}~d}~w|j                  $ r t        d	      t        j                   $ r t        d
      |j"                  $ r,}t        dt%        |      j&                   d| d|
       d}~ww xY w7 # |r||j)                          d{  7   w w w xY ww)aY  
    Async version of download_google_trends_rss for concurrent fetching.

    **Why use async?**
    - Fetch multiple countries/regions in parallel
    - 3x-100x faster for batch operations
    - Non-blocking for web applications (FastAPI, Django async)
    - Resource efficient - one thread handles many connections

    **Caching:** Results are cached for 5 minutes by default (shared with sync version).
    Use `cache=False` to bypass the cache and always fetch fresh data.

    **Performance comparison:**
    ```python
    # Sync (sequential) - 125 countries takes ~25 seconds
    for geo in COUNTRIES:
        trends = download_google_trends_rss(geo=geo)

    # Async (parallel) - 125 countries takes ~0.5 seconds
    results = await asyncio.gather(*[
        download_google_trends_rss_async(geo=geo)
        for geo in COUNTRIES
    ])
    ```

    Args:
        geo: Country/region code (e.g., 'US', 'GB', 'US-CA')
              Supports 125 countries + 51 US states
        output_format: Output format
            - 'dict' (default): List of dictionaries (Python native)
            - 'dataframe': pandas DataFrame (requires pandas)
            - 'json': JSON string
            - 'csv': CSV string
        include_images: Include image URLs and sources
        include_articles: Include news articles data
        max_articles_per_trend: Max news articles to include per trend (default: 5)
        session: Optional aiohttp.ClientSession for connection reuse.
                 If not provided, a new session is created per call.
                 For best performance with multiple requests, create and
                 reuse a single session.
        cache: Use cached results if available (default: True)
               Set to False to always fetch fresh data

    Returns:
        Depending on output_format:
        - 'dict': List[Dict] - List of trend dictionaries
        - 'dataframe': pd.DataFrame - pandas DataFrame
        - 'json': str - JSON string
        - 'csv': str - CSV string

    Raises:
        InvalidParameterError: If parameters are invalid
        DownloadError: If RSS fetch fails
        ImportError: If aiohttp is not installed

    Examples:
        >>> # Basic async usage
        >>> import asyncio
        >>> trends = asyncio.run(download_google_trends_rss_async(geo='US'))

        >>> # Fetch multiple countries in parallel (50x faster than sync)
        >>> async def fetch_all():
        ...     countries = ['US', 'GB', 'CA', 'AU', 'DE']
        ...     results = await asyncio.gather(*[
        ...         download_google_trends_rss_async(geo=geo)
        ...         for geo in countries
        ...     ])
        ...     return dict(zip(countries, results))
        >>> all_trends = asyncio.run(fetch_all())

        >>> # With session reuse for better performance
        >>> import aiohttp
        >>> async def fetch_with_session():
        ...     async with aiohttp.ClientSession() as session:
        ...         tasks = [
        ...             download_google_trends_rss_async(geo=geo, session=session)
        ...             for geo in ['US', 'GB', 'JP', 'DE', 'FR']
        ...         ]
        ...         return await asyncio.gather(*tasks)

        >>> # Use with FastAPI
        >>> from fastapi import FastAPI
        >>> app = FastAPI()
        >>> @app.get("/trends/{country}")
        ... async def get_trends(country: str):
        ...     return await download_google_trends_rss_async(geo=country)

        >>> # Bypass cache for fresh data
        >>> trends = await download_google_trends_rss_async(geo='US', cache=False)

    Note:
        Requires aiohttp: pip install trendspyg[async]
    r   NzTaiohttp is required for async operations.
Install with: pip install trendspyg[async]r   r   )totalr      r   r   r   r   r%   r   )aiohttpr`   r   r    r   re   rv   ClientSessionClientTimeoutstatusr&   readClientResponseErrorClientConnectorErrorr   asyncioTimeoutErrorClientErrorr   r   closerQ   r   )r   rR   r   r   r   r   r   r   r   r   r#   close_sessionr   r   r?   rA   s                   r    download_google_trends_rss_asyncr     su    L
 C
 C  ^5EG]^I%++I6$!-P`aa 8u
=C tOM)"?+g++-G!	{{30E0E0EB0O{P 0 0T\??c)&xSA (/0 0F W0--/!! %)5F Iv. &-AQRRa  
9
 	

80 00 0 0 0
 ** 	3qxxc22++ 	@  ## 	)  "" 	!$q'"2"2!3 43 u 	 " W0--/!! 1=s   H8D< AH8H *(E/ EE/ :EEEE/  E!E/ %H8<H=?H8<EH8E/ EE/ E, E#!E,(E/ /H>FH AH"'H		HH H8H5,H/-H55H8geosshow_progressdelayc                 2   	 ddl m } d}i }	| }
|r|r | dd	
      }
|
D ]G  }t        |d|||      }t        t        t           |      |	|<   |dkD  s3ddl	}|j                  |       I |	S # t        $ r" d}|rddl}t        d|j                         Y w xY w)um  
    Download RSS trends for multiple countries/regions with progress tracking.

    **Use this for batch operations** instead of looping manually.
    Shows a progress bar and returns results as a dictionary.

    Args:
        geos: List of geo codes (e.g., ['US', 'GB', 'CA', 'AU'])
        include_images: Include image URLs and sources
        include_articles: Include news articles data
        max_articles_per_trend: Max news articles per trend (default: 5)
        show_progress: Show tqdm progress bar (default: True)
        delay: Optional delay between requests in seconds (default: 0)
               Use 0.5-1.0 if you're fetching many countries to avoid rate limits

    Returns:
        Dict mapping geo code to list of trends: {'US': [...], 'GB': [...]}

    Raises:
        InvalidParameterError: If any geo code is invalid
        DownloadError: If any RSS fetch fails

    Examples:
        >>> # Fetch 5 countries with progress bar
        >>> results = download_google_trends_rss_batch(['US', 'GB', 'CA', 'AU', 'DE'])
        Fetching trends: 100%|██████████| 5/5 [00:01<00:00, 4.2 geo/s]
        >>> print(f"US has {len(results['US'])} trends")

        >>> # Fetch all countries (with small delay to be safe)
        >>> from trendspyg.config import COUNTRIES
        >>> results = download_google_trends_rss_batch(
        ...     list(COUNTRIES.keys()),
        ...     delay=0.5  # 0.5s between requests
        ... )
        Fetching trends: 100%|██████████| 125/125 [01:05<00:00, 1.9 geo/s]

    Warning:
        Fetching many countries (>50) without delay may trigger Google rate limits.
        If you get blocked, wait a few minutes and add delay=0.5 or delay=1.0.

    Note:
        For maximum speed with many countries, use the async version:
        `download_google_trends_rss_batch_async()` which fetches in parallel.
    r   tqdmTFN?Note: Install tqdm for progress bar: pip install trendspyg[cli]fileFetching trendsr   )descunitr   )r   rR   r   r   r   )r   r`   sysprintstderrr   r
   r   r   timesleep)r   r   r   r   r   r   r   has_tqdmr   resultsiteratorr   rA   r   s                 r    download_google_trends_rss_batchr     s    h# &(G H#45A + )-#9
 DJ/ 19JJu N;  #Szz#	#s   A+ +(BBmax_concurrentc                   K   	 ddl }ddl}	 ddlm} d}	i } |j                  |      d	d
dt        dt        ffd} |j                         4 d{   }| D cg c]  } |||       }}|rC|	rA  |j                  |      t        |      dd      2 3 d{   }| d{   \  }}|||<    |j                  |      D ]  }| d{   \  }}|||<    ddd      d{    |S # t        $ r t        d      w xY w# t        $ r# d}	|rddl}
t        d|
j                         Y w xY w7 c c}w 7 7 6 f7 t7 \# 1 d{  7  sw Y   |S xY ww)u*  
    Download RSS trends for multiple countries/regions in parallel with progress.

    **Fastest way to fetch multiple countries** - uses async/parallel requests.
    Shows a progress bar and returns results as a dictionary.

    Args:
        geos: List of geo codes (e.g., ['US', 'GB', 'CA', 'AU'])
        include_images: Include image URLs and sources
        include_articles: Include news articles data
        max_articles_per_trend: Max news articles per trend (default: 5)
        show_progress: Show tqdm progress bar (default: True)
        max_concurrent: Maximum concurrent requests (default: 10)
                       Lower this if you get rate limited (try 5 or 3)

    Returns:
        Dict mapping geo code to list of trends: {'US': [...], 'GB': [...]}

    Raises:
        InvalidParameterError: If any geo code is invalid
        DownloadError: If any RSS fetch fails
        ImportError: If aiohttp is not installed

    Examples:
        >>> # Fetch 5 countries in parallel (~0.3s total)
        >>> import asyncio
        >>> results = asyncio.run(
        ...     download_google_trends_rss_batch_async(['US', 'GB', 'CA', 'AU', 'DE'])
        ... )
        Fetching trends: 100%|██████████| 5/5 [00:00<00:00, 15.2 geo/s]

        >>> # Fetch ALL 125 countries in parallel (~2-5 seconds)
        >>> from trendspyg.config import COUNTRIES
        >>> results = asyncio.run(
        ...     download_google_trends_rss_batch_async(
        ...         list(COUNTRIES.keys()),
        ...         max_concurrent=10  # Limit concurrent requests
        ...     )
        ... )
        Fetching trends: 100%|██████████| 125/125 [00:03<00:00, 38.5 geo/s]

    Performance:
        - 5 countries: ~0.3 seconds (vs ~1s sync)
        - 125 countries: ~3-5 seconds (vs ~25s sync)
        - Uses connection pooling for efficiency

    Warning:
        High concurrency (>20) may trigger Google rate limits.
        If you get errors, reduce max_concurrent to 5 or 3.

    Note:
        Requires aiohttp: pip install trendspyg[async]
    r   NzZaiohttp is required for async batch operations.
Install with: pip install trendspyg[async]r   TFr   r   r   r   r   r   c           	         K   4 d {    t        |d|        d {   }||fcd d d       d {    S 7 27 7 	# 1 d {  7  sw Y   y xY ww)Nr   )r   rR   r   r   r   r   )r   )r   r   rA   r   r   r   	semaphores      r   	fetch_onez9download_google_trends_rss_batch_async.<locals>.fetch_one}  si      		 		;$-!1'= F ;		 		 				 		 		 		sN   A=AA?AAAAAAA	A
AAr   )r   r   r   )r   r   r`   tqdm.asyncior   r   r   r   	Semaphorestrtupler   as_completedra   )r   r   r   r   r   r   r   r   atqdmr   r   r   r   r   r   tasksresultrA   coror   s    ```               @r   &download_google_trends_rss_batch_asyncr   *  s    z
#. &(G!!!.1I
!8 
s 
u 
 
 %w$$& & &'489S7C(99X %$$$U+%j&	! & &f %+lV% -,,U3 &$(jV%&& && Ne  
9
 	

  #Szz#	#,&9& +! )!& & & && Ns   E"C4 D A E"D;E"E"D=2+EE!E"E%E+E,'EEE"E"-E
.E"4D		E"(D84E"7D88E"=EEEE
E"EEEE")TTrx   Tg        )TTrx   Tr   ),__doc__r   r   xml.etree.ElementTreeetreeElementTreer5   r   typingr   r   r   r   r   r	   r
   r_   rn   r   configr   r   r   
exceptionsr   r   r   utilsr   OutputFormatr   boolintr    r&   bytesrQ   rv   r   r   r   floatr   r   r   r!   r   <module>r      s>  "   " "  L L L 5 5 L L   9:Q	QQ Q  	Q
 	Q&
C &
c &
 &
 &
Rbb	b b 	b
  b 
$ZbJx
Jx
x
 x
 	x

 4:sN*+x
v+3 +3 +> "(!"#S	SS S 	S
  S S 4:sN*+SF "(!"#15xS	xSxS xS 	xS
  xS -.xS xS 4:sN*+xSz  !"#T
s)TT T  	T
 T T 
#tDz/Tr  !"#r
s)rr r  	r
 r r 
#tDz/rr!   