File size: 8,663 Bytes
d0382a4
 
 
 
 
c0285dc
73bab1d
d0382a4
 
 
c0285dc
 
 
 
d0382a4
 
 
c0285dc
 
 
 
 
d0382a4
 
 
 
 
 
 
 
 
c0285dc
 
 
 
 
 
d0382a4
c0285dc
 
 
 
 
 
 
 
 
d0382a4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c0285dc
d0382a4
 
5077538
d0382a4
 
c0285dc
 
 
 
 
 
d0382a4
 
 
 
 
 
 
 
 
 
eebd22e
c0df20e
429217d
c0df20e
 
d0382a4
 
 
 
 
 
 
 
 
 
 
 
c0285dc
d0382a4
 
 
 
 
c0285dc
d0382a4
 
c0285dc
d0382a4
 
 
 
 
 
 
 
c0285dc
0acbbb6
c0285dc
 
 
 
 
 
706a6a6
 
 
 
 
 
c0285dc
706a6a6
 
 
 
c0285dc
706a6a6
 
 
 
c0285dc
706a6a6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d0382a4
 
c0285dc
99379ee
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import streamlit as st
import torch
from transformers import GPT2Tokenizer, GPT2LMHeadModel
import base64
from datetime import datetime
import streamlit.components.v1 as components
import webbrowser


party_dict = {
    'AfD': './afd_gpt2',
    'Die Grünen': './gruene_gpt2',
    'CDU/CSU': './cdu_csu_gpt2',
    'die Linke': './linke_gpt2', 
}

picture_paths = {
    'blue_check': "./app_pictures//Twitter_Verified_Badge.png",
    'AfD': "./app_pictures//afd_logo.png",
    'CDU/CSU': "./app_pictures//cdu_logo.png",
    'Die Grünen': "./app_pictures//gruene_logo.png",
    'die Linke': "./app_pictures//linke_logo.png"
}

party_info = {
    "AfD": ("AfD", "@AfD"),
    "CDU/CSU": ("CDU", "@CDU"),
    "Die Grünen": ("Die Grünen", "@Die_Gruenen"),
    "die Linke": ("Die Linke", "@dieLinke")
}

topic_analysis_screenshots = {
    'AfD': './topic_analysis//afd_topic_analysis.png',
    'CDU/CSU': './topic_analysis//cdu_csu_topic_analysis.png',
    'Die Grünen': './topic_analysis//gruene_topic_analysis.png',
    'die Linke': './topic_analysis//linke_topic_analysis.png'
}

def initialize_session_state():
    if 'show_afd' not in st.session_state:
        st.session_state['show_afd'] = False
    if 'show_cdu_csu' not in st.session_state:
        st.session_state['show_cdu_csu'] = False
    if 'show_gruene' not in st.session_state:
        st.session_state['show_gruene'] = False
    if 'show_linke' not in st.session_state:
        st.session_state['show_linke'] = False

def generate_tweet(party, prompt):
    device = torch.device("cpu")
    model_path = party_dict[party]
    tokenizer = GPT2Tokenizer.from_pretrained(model_path)
    model = GPT2LMHeadModel.from_pretrained(model_path)
    input_ids = tokenizer.encode(prompt, return_tensors="pt").to(device)
    model.to(device)

    sample_outputs = model.generate(
        input_ids,
        do_sample=True,
        top_k=20,
        max_length=280,
        top_p=0.95,
        num_return_sequences=1,
        temperature=0.95,
        pad_token_id=tokenizer.eos_token_id
    )

    generated_tweet = tokenizer.decode(sample_outputs[0], skip_special_tokens=True)
    return generated_tweet
    
def get_base64_image(image_path):
    with open(image_path, "rb") as image_file:
        encoded_string = base64.b64encode(image_file.read())
    return encoded_string.decode('utf-8')

def main():
    st.title("Tweet GPT")
    st.sidebar.header("Analyzing Rhetorical Styles of German Political Parties")
    st.sidebar.write("This project analyzes rhetorical differences among major German parties by generating tweets tailored to their communication styles. Our motivation was to understand the nuances in language and messaging strategies, particularly the effective use of social media by right-wing parties to disseminate messages. We aimed to raise awareness of this issue and contribute to a better understanding of varying rhetorical approaches.")
    st.sidebar.markdown("#### Motivation")
    st.sidebar.markdown("- Understand language and Tweet nuances")
    st.sidebar.markdown("- Explore rhetorical differences and communication styles")
    st.sidebar.markdown("- Provide insights into crafting messages for supporters")
    st.sidebar.write("")
    st.sidebar.write("")
    st.sidebar.write("## W&B Training Evaluation Report")
    st.sidebar.markdown("The W&B reports provide a detailed assessment of our Tweet Generator's training process. They include various metrics and visualizations to analyze model performance, track its progress over time, and identify any weaknesses. ")
    with st.sidebar.expander("W&B Training Evaluation Report"):
        components.iframe("https://wandb.ai/ifisch/Tweet_Gen_v2_GPT2/reports/TweetGPT-Training-Evaluation-Process--Vmlldzo4MTU1NjU2?accessToken=4qiq23z5xycyyylaass0xge959em11ldry0deqqp6cr53ugqujfsh3xrzb1r8lsq", height=600, scrolling=True)

    tweet = ""
    prompt = ""

    col1, col2, col3 = st.columns([14, 1, 14])

    with col1:
        st.write("### Generate Tweets!")
        party = st.selectbox("Party", ["AfD", "CDU/CSU", "Die Grünen", "die Linke"], key='party')
        if st.button("Generate Tweet", key='generate', help="Click here to generate the tweet."):
            prompt = st.session_state.get("prompt","")
            if len(prompt.split()) < 3:
                st.warning("The prompt must consist of at least 3 words, and should be in one of the focus areas of the selected Party. (e.g AfD: immigration, Grüne: evironment)")
            else:
                tweet = generate_tweet(party, prompt)

    with col2: 
        st.write("")
    
    with col3:
        st.write("### Topic")
        prompt = st.text_area("Tweet Keyword", key="prompt")

    with st.container():
        current_date = datetime.now().strftime("%B %d, %Y")
        blue_check_base64 = get_base64_image(picture_paths['blue_check'])
        party_logo_base64 = get_base64_image(picture_paths[party])
        party_name, username = party_info[party]

        if tweet:
            tweet_display = f'''
            <div style="background-color: white; padding: 10px; font-family: Helvetica Neue, sans-serif; border: 1px solid #ccc; color: black; border-radius: 10px;">
                <div style="display: flex; align-items: center;">
                    <img src="data:image/png;base64,{party_logo_base64}" alt="{party_name} Logo" style="width: 40px; height: 40px; border-radius: 50%; margin-right: 10px;">
                    <div style="display: flex; align-items: center;">
                        <div style="display: flex; align-items: center; margin-right: 5px;">
                             <p style="font-weight: bold; color: black;">{party_name}<img src="data:image/png;base64,{blue_check_base64}" alt="checkmark" style="width: 20px; height: 20px; vertical-align: middle; margin-left: 2px; margin-right: 2px;"><span style="font-weight: normal; color: gray;"> {username}</span> <span style="font-weight: normal; color: gray;">{current_date}</span></p>
                </div>
                    </div>
                </div>
                <p style="color: black;">{tweet}</p>
            </div>
            '''
            st.markdown(tweet_display, unsafe_allow_html=True)

    st.write("## Our Insights")
    st.write("We developed a tweet generator for each party. For one part of our evaluation, we have generated 'Fake Tweets' by taking the first words of a 'Real Tweet' as input for our model. We have then performed Topic Modelling on the 'Fake Tweets' to evaluate if the model has picked up a party's rhetoric.")
    
    

   

    col1, col2, col3, col4 = st.columns(4)

    if col1.button("Die AfD Topic Analysis"):
        st.session_state.show_afd = not st.session_state.show_afd
        st.session_state.show_cdu_csu = False
        st.session_state.show_gruene = False
        st.session_state.show_linke = False
    if col2.button("CDU/CSU Topic Analysis"):
        st.session_state.show_afd = False
        st.session_state.show_cdu_csu = not st.session_state.show_cdu_csu
        st.session_state.show_gruene = False
        st.session_state.show_linke = False
    if col3.button("Die Grünen Topic Analysis"):
        st.session_state.show_afd = False
        st.session_state.show_cdu_csu = False
        st.session_state.show_gruene = not st.session_state.show_gruene
        st.session_state.show_linke = False
    if col4.button("Die Linke Topic Analysis"):
        st.session_state.show_afd = False
        st.session_state.show_cdu_csu = False
        st.session_state.show_gruene = False
        st.session_state.show_linke = not st.session_state.show_linke

    if st.session_state.show_afd:
        with open("./topic_analysis//afd_topics_trigram_bar_bert.html", "r", encoding='utf-8') as file:
            afd_html = file.read()
            components.html(afd_html, height=800, scrolling=True)
    if st.session_state.show_cdu_csu:
        with open("./topic_analysis//cdu_topics_trigram_bar_bert.html", "r", encoding='utf-8') as file:
            cdu_html = file.read()
            components.html(cdu_html, height=800, scrolling=True)
    if st.session_state.show_gruene:
        with open("./topic_analysis//gruene_topics_trigram_bar_bert.html", "r", encoding='utf-8') as file:
            gruene_html = file.read()
            components.html(gruene_html, height=800, scrolling=True)
    if st.session_state.show_linke:
        with open("./topic_analysis//linke_topics_trigram_bar_bert.html", "r", encoding='utf-8') as file:
            linke_html = file.read()
            components.html(linke_html, height=800, scrolling=True)

if __name__ == "__main__":
    initialize_session_state()
    main()