Spaces:
Sleeping
Sleeping
File size: 7,366 Bytes
d0382a4 c0285dc d0382a4 c0285dc d0382a4 c0285dc d0382a4 c0285dc d0382a4 c0285dc d0382a4 c0285dc d0382a4 c0285dc d0382a4 eebd22e c0df20e 429217d c0df20e d0382a4 c0285dc d0382a4 c0285dc d0382a4 c0285dc d0382a4 c0285dc 3107dd5 c0285dc 3107dd5 c0285dc 3107dd5 c0285dc 3107dd5 c0285dc 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 |
import streamlit as st
import torch
from transformers import GPT2Tokenizer, GPT2LMHeadModel
import base64
from datetime import datetime
import streamlit.components.v1 as components
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 messaging nuances")
st.sidebar.markdown("- Explore rhetorical differences and communication styles")
st.sidebar.markdown("- Provide insights into crafting messages for supporters")
st.sidebar.markdown("- Raise awareness of right-wing parties' social media use")
st.sidebar.write("Reference: https://www.zdf.de/nachrichten/politik/deutschland/afd-tiktok-erfolg-strategie-jugendliche-100.html")
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 that analyzes the dataset for each party. To view the insights, select the button to see the most common topics each party wrote about.")
col1, col2, col3, col4 = st.columns(4)
if col1.button("Die AfD Topic Analysis" ):
url = "./topic_analysis/afd_topics_trigram_bar_bert.html"
webbrowser.open_new_tab(url)
if col2.button("CDU/CSU Topic Analysis"):
url = "./topic_analysis/cdu_topics_trigram_bar_bert.html"
webbrowser.open_new_tab(url)
if col3.button("Die Grünen Topic Analysis"):
url = "./topic_analysis/gruene_topics_trigram_bar_bert.html"
webbrowser.open_new_tab(url)
if col4.button("Die Linke Topic Analysis"):
url = "./topic_analysis/linke_topics_trigram_bar_bert.html"
webbrowser.open_new_tab(url)
if __name__ == "__main__":
initialize_session_state()
main() |