Spaces:
Sleeping
Sleeping
Update app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225import requestsimport pandas as pdimport loggingimport gradio as grfrom typing import List, Dict, Anyfrom datetime import datetimefrom collections import Counterimport relogging.basicConfig(level=logging.INFO)class AmazonSuggestionExpander:def __init__(self):self.base_url = "https://completion.amazon.com/api/2017/suggestions"self.headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'}def get_amazon_suggestions(self, keyword: str, progress: gr.Progress = None) -> List[str]:try:params = {'mid': 'ATVPDKIKX0DER','alias': 'aps','prefix': keyword}response = requests.get(self.base_url, headers=self.headers, params=params)response.raise_for_status()data = response.json()suggestions = [item.get('suggestion', '') for item in data.get('suggestions', [])]return [s for s in suggestions if s] # Filter out empty suggestionsexcept requests.RequestException as e:logging.error(f"Request error: {str(e)}")raise Exception(f"Failed to fetch suggestions: {str(e)}")except Exception as e:logging.error(f"General error: {str(e)}")raise Exception(f"An error occurred: {str(e)}")class KeywordAnalyzer:def __init__(self):self.common_words = set(['the', 'and', 'for', 'with', 'in', 'on', 'at', 'to'])def analyze_suggestions(self, suggestions: List[str]) -> Dict[str, Any]:word_counts = [len(s.split()) for s in suggestions]lengths = [len(s) for s in suggestions]# Word frequency analysisall_words = ' '.join(suggestions).lower().split()word_freq = Counter([w for w in all_words if w not in self.common_words])analysis = {'total_count': len(suggestions),'avg_word_count': sum(word_counts) / len(suggestions) if suggestions else 0,'length_stats': {'avg_length': sum(lengths) / len(lengths) if lengths else 0,'max_length': max(lengths) if lengths else 0,'min_length': min(lengths) if lengths else 0},'common_words': dict(word_freq.most_common(10)),'price_mentions': sum(1 for s in suggestions if '$' in s or 'price' in s.lower()),'brand_mentions': sum(1 for s in suggestions if any(char.isupper() for char in s.split()))}return analysisdef format_analysis_output(analysis: Dict[str, Any]) -> str:"""Format analysis results as readable text"""output = "\nAnalysis Results:\n"output += f"Total Suggestions: {analysis['total_count']}\n"output += f"Average Words per Suggestion: {analysis['avg_word_count']:.1f}\n"output += f"Average Length: {analysis['length_stats']['avg_length']:.1f} characters\n"output += "\nMost Common Words:\n"for word, count in analysis['common_words'].items():output += f"- {word}: {count}\n"return outputdef create_visualization(analysis: Dict[str, Any]) -> str:"""Create HTML visualization of the analysis"""html = f"""<!DOCTYPE html><html><head><style>.analysis-container {{font-family: Arial, sans-serif;max-width: 800px;margin: 0 auto;padding: 20px;}}.metric-card {{background: #f5f5f5;border-radius: 8px;padding: 15px;margin: 10px 0;box-shadow: 0 2px 4px rgba(0,0,0,0.1);}}.word-cloud {{display: flex;flex-wrap: wrap;gap: 10px;margin: 10px 0;}}.word-item {{background: #e0e0e0;padding: 5px 10px;border-radius: 15px;font-size: 14px;}}h3 {{margin: 0 0 10px 0;color: #333;}}p {{margin: 5px 0;color: #666;}}</style></head><body><div class="analysis-container"><div class="metric-card"><h3>Overall Statistics</h3><p>Total Suggestions: {analysis['total_count']}</p><p>Average Words: {analysis['avg_word_count']:.1f}</p><p>Price Mentions: {analysis['price_mentions']}</p><p>Brand Mentions: {analysis['brand_mentions']}</p></div><div class="metric-card"><h3>Length Statistics</h3><p>Average Length: {analysis['length_stats']['avg_length']:.1f} characters</p><p>Maximum Length: {analysis['length_stats']['max_length']} characters</p><p>Minimum Length: {analysis['length_stats']['min_length']} characters</p></div><div class="metric-card"><h3>Most Common Words</h3><div class="word-cloud">{' '.join([f'<span class="word-item">{word} ({count})</span>'for word, count in analysis['common_words'].items()])}</div></div></div></body></html>"""return htmldef search_and_display(keyword: str, min_length: int = 0, progress: gr.Progress = gr.Progress()) -> tuple:"""Main function to handle the search and display process"""if not keyword:return "Please enter a keyword", None, Nonetry:# Initialize expander and get suggestionsexpander = AmazonSuggestionExpander()suggestions = expander.get_amazon_suggestions(keyword, progress)# Filter suggestions by minimum length if specifiedif min_length > 0:suggestions = [s for s in suggestions if len(s.split()) >= min_length]if not suggestions:return "No suggestions found", None, None# Analyze suggestionsanalyzer = KeywordAnalyzer()analysis = analyzer.analyze_suggestions(suggestions)# Create DataFrame and save to CSVdf = pd.DataFrame(suggestions, columns=['Suggestions'])df['Word Count'] = df['Suggestions'].str.split().str.len()timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")csv_filename = f"amazon_suggestions_{timestamp}.csv"df.to_csv(csv_filename, index=False)# Create output textoutput_text = f"Found {len(suggestions)} suggestions for '{keyword}':\n\n"for i, suggestion in enumerate(suggestions, 1):output_text += f"{i}. {suggestion}\n"# Add analysis resultsoutput_text += "\n" + format_analysis_output(analysis)try:# Create visualizationvisualization = create_visualization(analysis)except Exception as viz_error:logging.error(f"Visualization error: {str(viz_error)}")visualization = "<p>Error creating visualization</p>"return output_text, csv_filename, visualizationexcept Exception as e:logging.error(f"Error in search_and_display: {str(e)}")return f"Error occurred: {str(e)}", None, "<p>Error occurred during analysis</p>"# Create Gradio interfaceiface = gr.Interface(fn=search_and_display,inputs=[gr.Textbox(label="Enter keyword", placeholder="Type your keyword here..."),gr.Slider(minimum=0, maximum=10, step=1, label="Minimum word count filter", value=0)],outputs=[gr.Textbox(label="Results", lines=20),gr.File(label="Download CSV"),gr.HTML(label="Analysis Visualization")],title="Advanced Amazon Suggestion Expander",description="""Get expanded keyword suggestions from Amazon's search autocomplete with detailed analysis.Enter a keyword to see all related suggestions, analytics, and visualizations.""",examples=[["coffee maker", 2],["gaming laptop", 3],["yoga mat", 1]],cache_examples=True,theme=gr.themes.Soft())if __name__ == "__main__":iface.launch()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263import gradio as grfrom transformers import pipeline# Load Hugging Face models# Text generation for keyword suggestionskeyword_generator = pipeline("text-generation", model="gpt2", tokenizer="gpt2")# Sentiment analysis for niche review insightssentiment_analyzer = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")# Function to generate keyword suggestionsdef suggest_keywords(prompt):results = keyword_generator(prompt, max_length=50, num_return_sequences=3)suggestions = [res["text"].strip() for res in results]return "\n".join(suggestions)# Function to analyze sentiment of user-input textdef analyze_sentiment(text):sentiments = sentiment_analyzer(text)return sentiments# Gradio Interface Designwith gr.Blocks() as app:gr.Markdown("""# KDP Keyword Suggestion AppGenerate profitable KDP coloring book niches and analyze customer feedback!""")# Section for keyword generationwith gr.Row():with gr.Column():prompt_input = gr.Textbox(label="Enter Keyword Prompt",placeholder="E.g., coloring book for kids about",)keyword_output = gr.Textbox(label="Generated Keywords", lines=5)keyword_button = gr.Button("Generate Keywords")keyword_button.click(suggest_keywords, inputs=prompt_input, outputs=keyword_output)# Section for sentiment analysiswith gr.Row():with gr.Column():review_input = gr.Textbox(label="Enter Text for Sentiment Analysis",placeholder="Paste a customer review or feedback here...",lines=4,)sentiment_output = gr.Label(label="Sentiment Analysis Result")sentiment_button = gr.Button("Analyze Sentiment")sentiment_button.click(analyze_sentiment, inputs=review_input, outputs=sentiment_output)# Footergr.Markdown("Built with ❤️ using Hugging Face and Gradio for KDP enthusiasts!")# Launch the appapp.launch()
app.py+62-224