Spaces:
Sleeping
Sleeping
Update app.py
Browse files12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667import gradio as grfrom pytrends.request import TrendReqimport pandas as pdimport plotly.express as pximport time# Function to fetch trends and plot datadef fetch_trends(search_query='adult coloring books', region='US'):pytrends = TrendReq(hl='en-US', tz=360)# Set up the payload with the given query and regionpytrends.build_payload([search_query], cat=0, timeframe='today 12-m', geo=region)# Fetch related queriesrelated_queries = pytrends.related_queries()# Check if there are any top related queriesif related_queries and related_queries.get(search_query, {}).get('top') is not None:# Process the top related queries into a dataframedf = related_queries[search_query]['top']df = df[['query', 'value']] # Filter only relevant columnsdf = df.nlargest(10, 'value') # Get top 10 trending queries# Create the Plotly bar chart for visualizationfig = px.bar(df, x='query', y='value',title=f"Top 10 Trending Keywords for '{search_query}' in {region}",labels={'query': 'Keyword', 'value': 'Popularity Score'},color='value', color_continuous_scale='Viridis')fig.update_layout(xaxis_tickangle=-45)# Convert dataframe to a string for displaytop_keywords_str = df.to_string(index=False)# Return the plot and the keyword listreturn fig, top_keywords_strelse:return None, "No data found for the query in this region."# Create Gradio Interfaceiface = gr.Interface(fn=fetch_trends,inputs=[gr.Textbox(label="Enter Search Term",value="adult coloring books", # Default search termplaceholder="e.g. adult coloring books, mandala coloring, etc."),gr.Dropdown(choices=['US', 'UK', 'CA', 'AU', 'DE', 'FR', 'ES', 'IT', 'JP', 'BR', 'IN'],label="Select Region",value="US" # Set default region)],outputs=[gr.Plot(label="Trending Keywords Visualization"),gr.Textbox(label="Top 10 Trending Keywords", lines=10)],title="Google Trends Keyword Analyzer",description="Analyze trending keywords for any search term in various regions using Google Trends",theme="default")# Launch the interfaceiface.launch()123456789101112131415161718192021222324252627282930313233343536373839404142import gradio as grfrom pytrends.request import TrendReqimport matplotlib.pyplot as pltimport osdef get_trends(keyword):# Initialize the pytrends objectpytrends = TrendReq(hl="en-US", tz=360)# Build the payload and fetch the trends datapytrends.build_payload(kw_list=[keyword])df = pytrends.interest_over_time()# If there is no data, return a messageif df.empty:return "No data available for this keyword. Please try a different one."# Create a plotplt.figure(figsize=(20, 10))df[keyword].plot()plt.title(f"Google Trends for '{keyword}'", fontsize=20)plt.xlabel("Date", fontsize=16)plt.ylabel("Interest over time", fontsize=16)plt.grid(True)# Save the plot to a temporary fileplot_file = "/tmp/trends_plot.png"plt.savefig(plot_file)plt.close() # Close the plot to avoid display issuesreturn plot_file # Return the file path for Gradio to display the image# Set up the Gradio interfaceiface = gr.Interface(fn=get_trends,inputs=gr.Textbox(lines=1, label="Enter a keyword"),outputs=gr.Image(type="file"), # Output is now an image filetitle="Google Trends Visualizer",description="Enter a keyword to see its Google Trends data over time.")iface.launch()
app.py+30-55