TweetGPT / app.py
ifisch's picture
Update app.py
5077538 verified
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()