Spaces:
Sleeping
Sleeping
Update app.py
Browse files4 unmodified lines567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311324 unmodified lines1371381391401411421431441451461471481491501514 unmodified linesimport timefrom collections import defaultdictimport plotly.express as pximport plotly.graph_objects as goclass ColoringBookAnalyzer:def __init__(self):self.pytrends = TrendReq(hl='en-US', tz=360)self.coloring_categories = ['adult coloring books', 'mandala coloring', 'animal coloring','flower coloring', 'kids coloring books', 'fantasy coloring','anime coloring', 'pattern coloring', 'quotes coloring']def analyze_trends(self, timeframe='today 3-m', geo=''):trending_keywords = defaultdict(int)results = []for category in self.coloring_categories:try:self.pytrends.build_payload(kw_list=[category],cat=0,timeframe=timeframe,geo=geo)related_queries = self.pytrends.related_queries()if related_queries[category]['top'] is not None:for row in related_queries[category]['top'].itertuples():trending_keywords[row.query] += row.valueresults.append({'keyword': row.query,'score': row.value,'category': category})time.sleep(1)except Exception as e:continuereturn pd.DataFrame(results)def create_trends_plot(self, df):fig = px.bar(df.nlargest(15, 'score'),x='keyword',y='score',color='category',title='Top 15 Trending Coloring Book Keywords',labels={'keyword': 'Keyword', 'score': 'Popularity Score'})fig.update_layout(xaxis_tickangle=-45)return figdef get_competition_analysis(self, df):competition_data = []for _, row in df.nlargest(5, 'score').iterrows():try:self.pytrends.build_payload(kw_list=[row['keyword']],cat=0,timeframe='today 3-m')interest_over_time = self.pytrends.interest_over_time()if not interest_over_time.empty:avg_interest = interest_over_time[row['keyword']].mean()competition_level = "High" if avg_interest > 75 else "Medium" if avg_interest > 40 else "Low"competition_data.append({'keyword': row['keyword'],'average_interest': avg_interest,'competition_level': competition_level})time.sleep(1)except Exception as e:continuereturn pd.DataFrame(competition_data)def analyze_coloring_books(region):analyzer = ColoringBookAnalyzer()# Get trendstrends_df = analyzer.analyze_trends(geo=region)# Create visualizationtrends_plot = analyzer.create_trends_plot(trends_df)# Get competition analysiscompetition_df = analyzer.get_competition_analysis(trends_df)# Format resultstop_keywords = trends_df.nlargest(10, 'score')[['keyword', 'score', 'category']]top_keywords_str = top_keywords.to_string()competition_str = competition_df.to_string()# Generate recommendationsrecommendations = """Recommended Niches Based on Analysis:1. Complex Adult Coloring Books2. Simple Kids Coloring Books3. Mandala Collections4. Animal Themed Books5. Seasonal Coloring BooksTips for Success:- Focus on clear, high-quality designs- Create both simple and complex versions- Include 30-50 designs per book- Price between $6.99 - $12.99- Use relevant keywords in title and description"""return trends_plot, top_keywords_str, competition_str, recommendations# Create Gradio interfaceiface = gr.Interface(fn=analyze_coloring_books,inputs=[gr.Dropdown(choices=['US', 'UK', 'CA', 'AU', 'DE', 'FR', 'ES', 'IT'],4 unmodified linesoutputs=[gr.Plot(label="Trending Keywords Visualization"),gr.Textbox(label="Top 10 Trending Keywords", lines=10),gr.Textbox(label="Competition Analysis", lines=10),gr.Textbox(label="Recommendations", lines=10)],title="Coloring Book Trend Analyzer",description="Analyze trending keywords and competition in the coloring book market",theme="default")# For local testingif __name__ == "__main__":iface.launch()4 unmodified lines5678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182834 unmodified lines8889909192939495969798994 unmodified linesimport timefrom collections import defaultdictimport plotly.express as pxdef analyze_coloring_trends(region='US'):pytrends = TrendReq(hl='en-US', tz=360)coloring_categories = ['adult coloring books', 'mandala coloring','animal coloring', 'flower coloring','kids coloring books']trending_keywords = defaultdict(int)results = []for category in coloring_categories:try:pytrends.build_payload(kw_list=[category],cat=0,timeframe='today 3-m',geo=region)related_queries = pytrends.related_queries()if related_queries[category]['top'] is not None:for row in related_queries[category]['top'].itertuples():trending_keywords[row.query] += row.valueresults.append({'keyword': row.query,'score': row.value,'category': category})time.sleep(1)except Exception as e:continuedf = pd.DataFrame(results)# Create visualizationfig = px.bar(df.nlargest(15, 'score'),x='keyword',y='score',color='category',title='Top 15 Trending Coloring Book Keywords',labels={'keyword': 'Keyword', 'score': 'Popularity Score'})fig.update_layout(xaxis_tickangle=-45)# Format text resultstop_keywords = df.nlargest(10, 'score')[['keyword', 'score', 'category']]top_keywords_str = top_keywords.to_string()recommendations = f"""Top Trending Categories in {region}:1. {coloring_categories[0]}2. {coloring_categories[1]}3. {coloring_categories[2]}Recommended Actions:- Focus on these trending keywords- Create multiple variations- Target different skill levels- Consider seasonal themes"""return fig, top_keywords_str, recommendations# Create Gradio interfaceiface = gr.Interface(fn=analyze_coloring_trends,inputs=[gr.Dropdown(choices=['US', 'UK', 'CA', 'AU', 'DE', 'FR', 'ES', 'IT'],4 unmodified linesoutputs=[gr.Plot(label="Trending Keywords Visualization"),gr.Textbox(label="Top 10 Trending Keywords", lines=10),gr.Textbox(label="Recommendations", lines=10)],title="Coloring Book Trend Analyzer",description="Analyze trending keywords in the coloring book market",theme="default")# Launch the interfaceiface.launch()
app.py+62-114