import csv import gradio as gr import pandas as pd from sentiment_analyser import RandomAnalyser, RoBERTaAnalyser, ChatGPTAnalyser import matplotlib.pyplot as plt from sklearn.metrics import ConfusionMatrixDisplay, confusion_matrix def plot_bar(value_counts): fig, ax = plt.subplots(figsize=(6, 6)) value_counts.plot.barh(ax=ax) ax.bar_label(ax.containers[0]) plt.title('Frequency of Predictions') return fig def plot_confusion_matrix(y_pred, y_true): cm = confusion_matrix(y_true, y_pred, normalize='true') fig, ax = plt.subplots(figsize=(6, 6)) labels = [] for label in SENTI_MAPPING.keys(): if (label in y_pred.values) or (label in y_true.values): labels.append(label) disp = ConfusionMatrixDisplay(confusion_matrix=cm, display_labels=labels) disp.plot(cmap="Blues", values_format=".2f", ax=ax, colorbar=False) plt.title("Normalized Confusion Matrix") return fig def classify(num: int): samples_df = df.sample(num) X = samples_df['Text'].tolist() y = samples_df['Label'] roberta = MODEL_MAPPING[OUR_MODEL] y_pred = pd.Series(roberta.predict(X), index=samples_df.index) samples_df['Predict'] = y_pred bar = plot_bar(y_pred.value_counts()) cm = plot_confusion_matrix(y_pred, y) plt.close() return samples_df, bar, cm def analysis(Text): keys = [] values = [] for name, model in MODEL_MAPPING.items(): keys.append(name) values.append(SENTI_MAPPING[model.predict([Text])[0]]) return pd.DataFrame([values], columns=keys) def analyse_file(file): output_name = 'output.csv' with open(output_name, mode='w', newline='') as output: writer = csv.writer(output) header = ['Text', 'Label'] writer.writerow(header) model = MODEL_MAPPING[OUR_MODEL] with open(file.name) as f: for line in f: text = line[:-1] sentiment = model.predict([text]) writer.writerow([text, sentiment[0]]) return output_name MODEL_MAPPING = { 'Random': RandomAnalyser(), 'RoBERTa': RoBERTaAnalyser(), 'ChatGPT': RandomAnalyser(), } OUR_MODEL = 'RoBERTa' SENTI_MAPPING = { 'negative': '😭', 'neutral': '😶', 'positive': '🥰' } TITLE = "Sentiment Analysis on Software Engineer Texts" DESCRIPTION = ( "这里是第16组“睿王和他的五个小跟班”软工三迭代三模型演示页面。" "模型链接:[Cloudy1225/stackoverflow-roberta-base-sentiment]" "(https://huggingface.co/Cloudy1225/stackoverflow-roberta-base-sentiment) " ) MAX_SAMPLES = 64 df = pd.read_csv('./SOF4423.csv') with gr.Blocks(title=TITLE) as demo: gr.HTML(f"