Besimplestudio commited on
Commit
97bb8e6
·
verified ·
1 Parent(s): ff70492

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -93
app.py CHANGED
@@ -1,110 +1,52 @@
1
  import gradio as gr
2
  from pytrends.request import TrendReq
3
  import pandas as pd
4
- from collections import defaultdict
5
  import plotly.express as px
6
  import time
7
 
8
- def analyze_coloring_trends(search_query='adult coloring books', region='US'):
9
- # Initialize Google Trends connection
10
  pytrends = TrendReq(hl='en-US', tz=360)
11
 
12
- # Predefined categories for the search query
13
- predefined_categories = [
14
- 'adult coloring books', 'mandala coloring',
15
- 'animal coloring', 'flower coloring',
16
- 'kids coloring books'
17
- ]
18
 
19
- # If the search query matches one of the predefined categories, use it
20
- if search_query.lower() in predefined_categories:
21
- coloring_categories = [search_query]
22
- else:
23
- # Otherwise, use the user-provided search term as a custom query
24
- coloring_categories = [search_query]
25
-
26
- trending_keywords = defaultdict(int)
27
- results = []
28
 
29
- for category in coloring_categories:
30
- try:
31
- print(f"Fetching data for category: {category} in region: {region}")
32
-
33
- # Build payload with extended timeframe to capture more trends
34
- pytrends.build_payload(
35
- kw_list=[category],
36
- cat=0,
37
- timeframe='today 12-m', # Extended timeframe for better results
38
- geo=region
39
- )
40
-
41
- # Fetch related queries
42
- related_queries = pytrends.related_queries()
43
- print(f"Related queries for {category}: {related_queries}")
44
-
45
- # Ensure data exists for the category
46
- if related_queries and related_queries.get(category, {}).get('top') is not None:
47
- for row in related_queries[category]['top'].itertuples():
48
- trending_keywords[row.query] += row.value
49
- results.append({
50
- 'keyword': row.query,
51
- 'score': row.value,
52
- 'category': category
53
- })
54
- else:
55
- print(f"No data for category: {category} in region: {region}")
56
-
57
- time.sleep(3) # Increase delay to avoid rate limiting
58
 
59
- except Exception as e:
60
- print(f"Error fetching data for {category}: {e}")
61
- continue
62
-
63
- # Create DataFrame from results
64
- df = pd.DataFrame(results)
65
-
66
- # If DataFrame is empty, handle the case gracefully
67
- if df.empty:
68
- print("No data available for the selected category in this region.")
69
- return gr.Plot.update(), "No data available for the selected category in this region.", ""
70
-
71
- # Create bar chart visualization
72
- fig = px.bar(
73
- df.nlargest(15, 'score'),
74
- x='keyword',
75
- y='score',
76
- color='category',
77
- title='Top 15 Trending Coloring Book Keywords',
78
- labels={'keyword': 'Keyword', 'score': 'Popularity Score'}
79
- )
80
- fig.update_layout(xaxis_tickangle=-45)
81
-
82
- # Prepare top 10 keywords for display
83
- top_keywords = df.nlargest(10, 'score')[['keyword', 'score', 'category']]
84
- top_keywords_str = top_keywords.to_string(index=False)
85
-
86
- # Recommendations based on the analysis
87
- recommendations = f"""
88
- Top Trending Categories in {region}:
89
- 1. {coloring_categories[0]}
90
-
91
- Recommended Actions:
92
- - Focus on these trending keywords
93
- - Create multiple variations
94
- - Target different skill levels
95
- - Consider seasonal themes
96
- """
97
 
98
- return fig, top_keywords_str, recommendations
 
99
 
100
- # Create Gradio interface with search bar
101
  iface = gr.Interface(
102
- fn=analyze_coloring_trends,
103
  inputs=[
104
  gr.Textbox(
105
  label="Enter Search Term",
106
  value="adult coloring books", # Default search term
107
- placeholder="e.g. adult coloring books, animal coloring, etc."
108
  ),
109
  gr.Dropdown(
110
  choices=['US', 'UK', 'CA', 'AU', 'DE', 'FR', 'ES', 'IT', 'JP', 'BR', 'IN'],
@@ -114,11 +56,10 @@ iface = gr.Interface(
114
  ],
115
  outputs=[
116
  gr.Plot(label="Trending Keywords Visualization"),
117
- gr.Textbox(label="Top 10 Trending Keywords", lines=10),
118
- gr.Textbox(label="Recommendations", lines=10)
119
  ],
120
- title="Coloring Book Trend Analyzer",
121
- description="Analyze trending keywords in the coloring book market",
122
  theme="default"
123
  )
124
 
 
1
  import gradio as gr
2
  from pytrends.request import TrendReq
3
  import pandas as pd
 
4
  import plotly.express as px
5
  import time
6
 
7
+ # Function to fetch trends and plot data
8
+ def fetch_trends(search_query='adult coloring books', region='US'):
9
  pytrends = TrendReq(hl='en-US', tz=360)
10
 
11
+ # Set up the payload with the given query and region
12
+ pytrends.build_payload([search_query], cat=0, timeframe='today 12-m', geo=region)
 
 
 
 
13
 
14
+ # Fetch related queries
15
+ related_queries = pytrends.related_queries()
16
+
17
+ # Check if there are any top related queries
18
+ if related_queries and related_queries.get(search_query, {}).get('top') is not None:
19
+ # Process the top related queries into a dataframe
20
+ df = related_queries[search_query]['top']
21
+ df = df[['query', 'value']] # Filter only relevant columns
22
+ df = df.nlargest(10, 'value') # Get top 10 trending queries
23
 
24
+ # Create the Plotly bar chart for visualization
25
+ fig = px.bar(
26
+ df, x='query', y='value',
27
+ title=f"Top 10 Trending Keywords for '{search_query}' in {region}",
28
+ labels={'query': 'Keyword', 'value': 'Popularity Score'},
29
+ color='value', color_continuous_scale='Viridis'
30
+ )
31
+ fig.update_layout(xaxis_tickangle=-45)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32
 
33
+ # Convert dataframe to a string for display
34
+ top_keywords_str = df.to_string(index=False)
35
+
36
+ # Return the plot and the keyword list
37
+ return fig, top_keywords_str
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
 
39
+ else:
40
+ return None, "No data found for the query in this region."
41
 
42
+ # Create Gradio Interface
43
  iface = gr.Interface(
44
+ fn=fetch_trends,
45
  inputs=[
46
  gr.Textbox(
47
  label="Enter Search Term",
48
  value="adult coloring books", # Default search term
49
+ placeholder="e.g. adult coloring books, mandala coloring, etc."
50
  ),
51
  gr.Dropdown(
52
  choices=['US', 'UK', 'CA', 'AU', 'DE', 'FR', 'ES', 'IT', 'JP', 'BR', 'IN'],
 
56
  ],
57
  outputs=[
58
  gr.Plot(label="Trending Keywords Visualization"),
59
+ gr.Textbox(label="Top 10 Trending Keywords", lines=10)
 
60
  ],
61
+ title="Google Trends Keyword Analyzer",
62
+ description="Analyze trending keywords for any search term in various regions using Google Trends",
63
  theme="default"
64
  )
65