File size: 3,346 Bytes
d4ac33d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import gradio as gr
import tweepy
import pandas as pd
import matplotlib.pyplot as plt
from wordcloud import WordCloud
from transformers import pipeline

# Hugging Face Models
sentiment_analyzer = pipeline("sentiment-analysis")
summarizer = pipeline("summarization", model="facebook/bart-large-cnn")

# Twitter API Setup (replace with your Bearer Token)
BEARER_TOKEN = "AAAAAAAAAAAAAAAAAAAAAN3g3wEAAAAA33Fzyb2P1rQzFwmXPIh4OHIw7e8%3DJY5zPrXhmzlht200jSaA8dgQixPX6idTvk2HWX0LgKwruozAsC"
client = tweepy.Client(bearer_token=BEARER_TOKEN)

# Function: Fetch Tweets
def fetch_tweets(username, count=50):
    tweets = client.get_users_tweets(
        id=client.get_user(username=username).data.id,
        max_results=min(count, 100)
    )
    texts = [t.text for t in tweets.data] if tweets.data else []
    df = pd.DataFrame(texts, columns=["text"])
    return df

# Function: Load file (CSV/XLSX)
def load_file(file):
    if file.name.endswith(".csv"):
        return pd.read_csv(file.name)
    elif file.name.endswith(".xlsx"):
        return pd.read_excel(file.name)
    else:
        return pd.DataFrame(columns=["text"])

# Function: Clean text
def clean_text(df):
    df["cleaned_text"] = (
        df["text"].astype(str)
        .str.replace(r"http\S+", "", regex=True)
        .str.replace(r"@\w+", "", regex=True)
        .str.replace(r"[^A-Za-z0-9\s]", "", regex=True)
        .str.strip()
    )
    return df

# Function: Sentiment, Summary & WordCloud
def analyze_data(df):
    if df.empty:
        return "No data found", None, None
    
    df = clean_text(df)

    # Sentiment
    df["sentiment"] = df["cleaned_text"].apply(
        lambda x: sentiment_analyzer(x[:512])[0]["label"] if len(x) > 0 else "neutral"
    )

    # Summary (combine text for summarization)
    full_text = " ".join(df["cleaned_text"].tolist())[:3000]
    summary = summarizer(full_text, max_length=100, min_length=30, do_sample=False)[0]["summary_text"]

    # WordCloud
    text_for_wc = " ".join(df["cleaned_text"].tolist())
    wordcloud = WordCloud(width=800, height=400, background_color="white").generate(text_for_wc)
    plt.figure(figsize=(8, 4))
    plt.imshow(wordcloud, interpolation="bilinear")
    plt.axis("off")
    plt.tight_layout()
    plt.savefig("wordcloud.png")

    return summary, df, "wordcloud.png"

# Gradio UI
with gr.Blocks() as demo:
    gr.Markdown("# 📊 Twitter & File Sentiment Analysis Prototype")

    with gr.Tab("Fetch Tweets"):
        username = gr.Textbox(label="Twitter Username (without @)")
        count = gr.Slider(10, 100, value=50, step=10, label="Number of Tweets")
        btn_fetch = gr.Button("Fetch & Analyze")
        summary_out = gr.Textbox(label="Summary")
        df_out = gr.Dataframe()
        img_out = gr.Image()

    with gr.Tab("Upload File"):
        file_in = gr.File(label="Upload CSV/XLSX")
        btn_file = gr.Button("Analyze File")
        summary_out2 = gr.Textbox(label="Summary")
        df_out2 = gr.Dataframe()
        img_out2 = gr.Image()

    # Actions
    btn_fetch.click(
        lambda u, c: analyze_data(fetch_tweets(u, c)),
        inputs=[username, count],
        outputs=[summary_out, df_out, img_out],
    )
    btn_file.click(
        lambda f: analyze_data(load_file(f)),
        inputs=[file_in],
        outputs=[summary_out2, df_out2, img_out2],
    )

demo.launch()