Lsai2122/dev
0
1import gradio as gr2import pandas as pd3# NOTE: These import paths rely on the structure you had before.4from endpoints.models.indicbert import analyze_sentiments5from endpoints.models.summarization_flan25.main import generate_aggregated_summary6 7# --- Core Logic Wrappers ---8 9def get_sentiment_gradio(comments_text: str) -> pd.DataFrame:10 """11 Takes text input (comments separated by newlines) and runs sentiment analysis.12 Safely handles percentage values that might be returned as strings or non-numeric types.13 """14 # 1. Parse Input: Split the single string into a list of comments15 comments = [c.strip() for c in comments_text.split('\n') if c.strip()]16 17 if not comments:18 # Return an empty DataFrame for empty input19 return pd.DataFrame({'Comment': [], 'Sentiment': [], 'Confidence (%)': []})20 21 try:22 # 2. Run the core logic23 # results and percentages are returned by analyze_sentiments24 results, percentages = analyze_sentiments(comments)25 26 # 3. Safely format percentages27 formatted_percentages = []28 for p in percentages:29 try:30 # Attempt to convert to float. Treat empty/None value as 0.031 value = float(p) if p else 0.032 # Format to two decimal places and append the percentage symbol33 formatted_percentages.append(f"{value * 100:.2f}%")34 except ValueError:35 # If conversion fails (e.g., "N/A", "Error"), use a placeholder36 formatted_percentages.append("N/A")37 38 # 4. Build the DataFrame39 data = {40 "Comment": comments,41 "Sentiment": results,42 "Confidence (%)": formatted_percentages 43 }44 return pd.DataFrame(data)45 46 except Exception as e:47 # Catch all other potential errors (like ImportErrors or model crashes)48 raise gr.Error(f"Sentiment analysis failed: {str(e)}")49 50 51def get_summary_gradio(comments_text: str) -> str:52 """53 Takes text input (comments separated by newlines) and returns a single summary string.54 """55 # 1. Parse Input: Split the single string into a list of comments56 comments = [c.strip() for c in comments_text.split('\n') if c.strip()]57 58 if not comments:59 return "Please enter comments to generate a summary."60 61 try:62 # 2. Run the core logic63 result = generate_aggregated_summary(comments)64 65 # 3. Format Output: Return the summary string66 return result67 68 except Exception as e:69 raise gr.Error(f"Summary generation failed: {str(e)}")70 71 72# --- Gradio Interface Setup ---73 74# Tab 1: Sentiment Analysis (Index 0, accessible via /run/predict)75sentiment_interface = gr.Interface(76 fn=get_sentiment_gradio,77 inputs=gr.Textbox(78 lines=10, 79 label="Enter Comments (one per line)",80 value="This product is excellent and arrived quickly.\nI am disappointed with the customer service.\nIt's fine, nothing special either way."81 ),82 outputs=gr.Dataframe(83 headers=["Comment", "Sentiment", "Confidence (%)"], 84 col_count=(3, "fixed"), 85 label="Sentiment Analysis Results"86 ),87 title="Sentiment Analysis (IndicBERT)",88 description="Analyze the sentiment of multiple comments and view the confidence score."89)90 91# Tab 2: Summarization (Index 1, accessible via /run/predict_1)92summary_interface = gr.Interface(93 fn=get_summary_gradio,94 inputs=gr.Textbox(95 lines=10, 96 label="Enter Comments for Aggregated Summary (one per line)",97 value="The battery life is amazing, lasting two full days.\nThe camera is poor in low light conditions.\nThe screen quality is top-notch, very bright and clear."98 ),99 outputs=gr.Textbox(100 label="Aggregated Summary",101 lines=5102 ),103 title="Aggregated Summarization (FLAN-T5)",104 description="Generate a single summary covering all points from the input comments."105)106 107# Combine interfaces into a Tabbed Interface108demo = gr.TabbedInterface([sentiment_interface, summary_interface], ["Sentiment Analysis", "Summarization"])109 110if __name__ == "__main__":111 demo.launch(server_name="0.0.0.0", server_port=7860, share=False, ssr_mode=False)