Mohammed Foud commited on
Commit ·
b3ed9e6
1
Parent(s): 7f87155
first commit
Browse files10 unmodified lines11121314151631 unmodified lines48495051525354555689 unmodified lines14614714814915015115215315415537 unmodified lines19319419519619719819911 unmodified lines2112122132142152162172182194 unmodified lines22422522622722822910 unmodified linesfrom textblob import TextBlobfrom collections import defaultdictfrom tabulate import tabulate# Load models and initialize componentsmodel_path = "./final_model"31 unmodified linesreturn "Error: Could not load dataset.csv"try:sample_reviews = df['reviews.text'].sample(n=min(50, len(df))).fillna('').tolist()sample_text = '\n'.join(sample_reviews)return generate_category_summary(sample_text)except Exception as e:return f"Error generating initial summary: {str(e)}"89 unmodified lines# Original sentiment analysisdf, plot_html = analyze_reviews_sentiment(reviews_text)# Generate summarysummary = generate_category_summary(reviews_text)return df, plot_html, summarydef analyze_reviews_sentiment(reviews_text):reviews = [r.strip() for r in reviews_text.split('\n') if r.strip()]37 unmodified lineswith gr.Tab("Review Analysis"):# Add initial dataset summarygr.Markdown("## Dataset Overview")gr.Markdown(initial_summary)gr.Markdown("## Analyze New Reviews")reviews_input = gr.Textbox(11 unmodified linesplot_output = gr.HTML(label="Sentiment Distribution")with gr.Column():summary_output = gr.Textbox(label="Review Summary",lines=5)analyze_button.click(4 unmodified linesreturn demo# Create and launch the interfaceif __name__ == "__main__":demo = create_interface()10 unmodified lines111213141516171831 unmodified lines505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910089 unmodified lines19019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222337 unmodified lines26126226326426526626711 unmodified lines2792802812822832842852864 unmodified lines29129229329429529629729829930030130230330430530630730830931031131231331431531631731810 unmodified linesfrom textblob import TextBlobfrom collections import defaultdictfrom tabulate import tabulatefrom sklearn.feature_extraction.text import TfidfVectorizerfrom sklearn.cluster import KMeans# Load models and initialize componentsmodel_path = "./final_model"31 unmodified linesreturn "Error: Could not load dataset.csv"try:# Generate summaries for all categoriessummaries = generate_category_summaries(df)# Convert summaries to HTML format for Gradiohtml_output = []for category, tables in summaries.items():html_output.append(f"<h2>CATEGORY: {category}</h2>")for table in tables:html_output.append(f"<h3>{table['section']}</h3>")# Convert table to HTML using tabulatetable_html = tabulate(table['data'],headers=table['headers'],tablefmt="html",stralign="left",numalign="center")# Add some CSS stylingstyled_table = f"""<style>table {{border-collapse: collapse;margin: 15px 0;width: 100%;}}th, td {{padding: 8px;border: 1px solid #ddd;text-align: left;}}th {{background-color: #f5f5f5;}}tr:nth-child(even) {{background-color: #f9f9f9;}}</style>{table_html}"""html_output.append(styled_table)html_output.append("<hr>") # Add separator between categoriesreturn "\n".join(html_output)except Exception as e:return f"Error generating initial summary: {str(e)}"89 unmodified lines# Original sentiment analysisdf, plot_html = analyze_reviews_sentiment(reviews_text)# Create a temporary DataFrame with the new reviewstemp_df = pd.DataFrame({'text': reviews_text.split('\n'),'rating': [3] * len(reviews_text.split('\n')), # Default neutral rating'name': ['New Review'] * len(reviews_text.split('\n')),'cluster_name': ['New Reviews'] * len(reviews_text.split('\n'))})# Generate summary tablessummaries = generate_category_summaries(temp_df)# Convert summaries to HTMLhtml_output = []for category, tables in summaries.items():for table in tables:html_output.append(f"<h3>{table['section']}</h3>")table_html = tabulate(table['data'],headers=table['headers'],tablefmt="html",stralign="left",numalign="center")html_output.append(table_html)summary_html = "\n".join(html_output)return df, plot_html, summary_htmldef analyze_reviews_sentiment(reviews_text):reviews = [r.strip() for r in reviews_text.split('\n') if r.strip()]37 unmodified lineswith gr.Tab("Review Analysis"):# Add initial dataset summarygr.Markdown("## Dataset Overview")gr.HTML(initial_summary) # Changed from gr.Markdown to gr.HTMLgr.Markdown("## Analyze New Reviews")reviews_input = gr.Textbox(11 unmodified linesplot_output = gr.HTML(label="Sentiment Distribution")with gr.Column():summary_output = gr.HTML( # Changed from gr.Textbox to gr.HTMLlabel="Review Summary")analyze_button.click(4 unmodified linesreturn demodef add_clusters_to_df(df):"""Add cluster names to the DataFrame if they don't exist"""# Create text featuresvectorizer = TfidfVectorizer(max_features=1000, stop_words='english')text_features = vectorizer.fit_transform(df['text'])# Perform clusteringn_clusters = 4 # You can adjust thiskmeans = KMeans(n_clusters=n_clusters, random_state=42)df['cluster_name'] = kmeans.fit_predict(text_features)# Map cluster numbers to namescluster_names = {0: "Electronics",1: "Home & Kitchen",2: "Books & Media",3: "Other Products"}df['cluster_name'] = df['cluster_name'].map(cluster_names)return df# Create and launch the interfaceif __name__ == "__main__":demo = create_interface()
app.py+99-10