OrganizingForChange commited on
Commit
85832e5
·
verified ·
1 Parent(s): 2d3a36c

Upload 11 files

Browse files
app.py CHANGED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import openai
3
+ import os
4
+ import tiktoken
5
+
6
+ def read_file(path):
7
+ with open(path, "r", encoding="utf-8") as f:
8
+ return f.read().strip()
9
+
10
+ SYSTEM_PROMPT_START = read_file("system_prompt_start.txt")
11
+ SYSTEM_PROMPT_SPAM_FILTER = "\n" + read_file("system_prompt_spam_filter.txt")
12
+ SYSTEM_PROMPT_FEEDBACK = "\n" + read_file("system_prompt_feedback.txt")
13
+ TARGET_OPTIONS_DIR = "target_options"
14
+
15
+ def get_target_options():
16
+ options = []
17
+ for filename in os.listdir(TARGET_OPTIONS_DIR):
18
+ if filename.endswith(".txt"):
19
+ options.append(filename[:-4])
20
+ options.sort()
21
+ return options
22
+
23
+ def get_target_prompt(option_name):
24
+ file_path = os.path.join(TARGET_OPTIONS_DIR, option_name + ".txt")
25
+ if os.path.exists(file_path):
26
+ return read_file(file_path)
27
+ return ""
28
+
29
+ def compose_system_prompt(target, additional_sysinfo, consider_spam, feedback, user_message):
30
+ length_instruction = (
31
+ "\nPlease keep your rewritten message about the same length as the input message."
32
+ )
33
+ prompt = f"{SYSTEM_PROMPT_START}\n"
34
+ prompt += get_target_prompt(target) + "\n"
35
+ if additional_sysinfo.strip():
36
+ prompt += additional_sysinfo.strip() + "\n"
37
+ prompt += length_instruction
38
+ if consider_spam:
39
+ prompt += SYSTEM_PROMPT_SPAM_FILTER
40
+ if feedback:
41
+ prompt += SYSTEM_PROMPT_FEEDBACK
42
+ return prompt.strip()
43
+
44
+ def run_llm(api_key, target, consider_spam, feedback, additional_sysinfo, user_message):
45
+ if not api_key or len(api_key.strip()) < 20:
46
+ return "Please enter a valid OpenAI API key before running."
47
+ if not user_message.strip():
48
+ return "Please enter a message."
49
+ # Use the user-supplied API key to create OpenAI client
50
+ try:
51
+ client = openai.OpenAI(api_key=api_key)
52
+ except Exception as e:
53
+ return f"Could not initialize OpenAI client: {e}"
54
+ prompt = compose_system_prompt(target, additional_sysinfo, consider_spam, feedback, user_message)
55
+ try:
56
+ completion = client.chat.completions.create(
57
+ model="gpt-4.1",
58
+ messages=[
59
+ {"role": "system", "content": prompt},
60
+ {"role": "user", "content": user_message}
61
+ ]
62
+ )
63
+ return completion.choices[0].message.content.strip()
64
+ except Exception as e:
65
+ return f"An error occurred: {e}"
66
+
67
+ target_options = get_target_options()
68
+
69
+ with gr.Blocks() as demo:
70
+
71
+ # Logo-and-instructions row
72
+ with gr.Row():
73
+ with gr.Column(scale=2):
74
+ gr.Markdown("""
75
+ ## Experimental LLM Segment Messaging App
76
+ This tool helps you improve, adapt, and review your written messaging—emails, newsletters, petitions, announcements, and more—using a state-of-the-art AI language model. It is based on the excellent research on segmentation by [EcoAnalytics](https://ecoanalyticscanada.org/).
77
+
78
+ You can select your intended audience, add optional instructions for the AI, and receive an output that is tailored for clarity, effectiveness, and your communication goal.
79
+
80
+ The system will reformulate your message to match the length of your input (not longer), and if you ask for feedback, the response will contain a feedback section of appropriate length after your main message. This feedback (should) always come at the end and follow three dashes ('---').
81
+
82
+ Selecting the Consider Spam Filters button will include instructions to the LLM to consider ways to avoid spam filters.
83
+
84
+ When you are ready, just hit the "Generate Targetted Message" button and wait a moment. If you are unhappy with the result, or want to see another version, you can resubmit the same information for a different result.
85
+
86
+ This tool is “expert adjacent”—it is designed to support people with some experience in communications work, not to generate communications materials from scratch.
87
+
88
+ This tool was created by [Organizing for Change](https://www.organizingforchange.org). For support, contact Sebastian at sebastian@organizingforchange.org.
89
+
90
+ **API Key Instructions**
91
+
92
+ - If you received a link to this app, you may also have received an OpenAI API key you can use.
93
+ - (Optional) If you did not get a key, you can create your own at [OpenAI API Keys](https://platform.openai.com/api-keys).
94
+ - (Optional) If creating a key, you will need to create an account and connect a payment method. Don't worry, this program does not consume many credits per run.
95
+ - Copy and paste your key in the box below. Your API key will only be used for this session and is never stored.
96
+ """)
97
+ with gr.Column(scale=1):
98
+ gr.Image(
99
+ "logo.png",
100
+ elem_id="logo-img",
101
+ show_label=False,
102
+ show_download_button=False,
103
+ show_share_button=False, # hide share
104
+ )
105
+ with gr.Row():
106
+ api_key = gr.Textbox(
107
+ type="password",
108
+ placeholder="Paste your OpenAI API key here...",
109
+ label="OpenAI API Key",
110
+ info="Enter the key you received, or get one at https://platform.openai.com/api-keys"
111
+ )
112
+ with gr.Row():
113
+ target = gr.Dropdown(
114
+ choices=target_options,
115
+ value=target_options[0] if target_options else None,
116
+ label="Target Audience",
117
+ info="Select your message's intended audience."
118
+ )
119
+ with gr.Row():
120
+ consider_spam = gr.Checkbox(
121
+ label="Consider Spam Filters?",
122
+ info="Check to ensure the system considers spam filters. Select this if you want the LLM to consider ways to avoid spam filters (for emails)."
123
+ )
124
+ with gr.Row():
125
+ feedback = gr.Checkbox(
126
+ label="Request Feedback from LLM?",
127
+ info="If checked, the LLM will provide additional feedback and suggestions about your message after rewriting it.",
128
+ value=True # This makes it checked by default!
129
+ )
130
+
131
+ additional_sysinfo = gr.Textbox(
132
+ lines=3,
133
+ placeholder="(Optional) Add extra instructions to system prompt...",
134
+ label="Additional System Prompt Info",
135
+ info="Extra context or rules for the system prompt. You should include at least what the type of comms product you are inputting if it isn't otherwise obvious (e.g. entering 'This is for a petition' if you are entering petition text). You can also provide additional context for the LLM to pull from that might not be in your current comms product. You can also provide other guidance like 'Keep it short!'",
136
+ )
137
+
138
+ user_message = gr.Textbox(
139
+ lines=10,
140
+ placeholder="Paste your message here...",
141
+ label="Input Message",
142
+ info="Paste or write your actual message here."
143
+ )
144
+
145
+ submit = gr.Button("Generate Targetted Message", variant="primary")
146
+ output = gr.Textbox(
147
+ lines=10,
148
+ label="Message as Modified by LLM for Target Audience",
149
+ info="The LLM’s refined response will appear here. You can regenerate the response and get something new by clicking 'Generate Targetted Message' again."
150
+ )
151
+
152
+ submit.click(
153
+ fn=run_llm,
154
+ inputs=[api_key, target, consider_spam, feedback, additional_sysinfo, user_message],
155
+ outputs=output
156
+ )
157
+
158
+ if __name__ == "__main__":
159
+ demo.launch(share=True)
logo.png ADDED
requirements.txt ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ gradio>=3.60
2
+ openai>=1.16
3
+ tiktoken>=0.6
system_prompt_feedback.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ At the end of the new text, put a horizontal line and then provide constructive feedback explaining why certains changes were made and how the message could be further improved. At the top of this section, below the horizontal line, label is "Feedback from AI"
system_prompt_spam_filter.txt ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You will also try to modify the message to avoid spam filters if possible.
2
+
3
+ Write accurate and engaging subject lines
4
+ While subject lines affect your open rates, they also play a role in whether your emails will be flagged as spam. Someone can quickly look at your email subject line and decide to mark the email as spam without even opening it.
5
+
6
+ That’s why you need to take extra care with your subject lines so you don’t end up creating a negative impression with your email subscribers. Here’s what you need to do to create impactful email subject lines:
7
+
8
+ Don’t use all caps in the subject line
9
+ Avoid exclamation marks
10
+ Avoid over-using spam trigger words like “free,” “now,” and “guarantee”
11
+ Personalize the subject line to the recipient
12
+ Make the subject line as descriptive as possible
13
+ Not sure if your subject lines pass the spam test? Check your subject lines in seconds with our free email subject line tester.
14
+
15
+ Lose words that trigger spam filters
16
+ When writing your email copy, you want to limit the use of spammy words that can make readers flag your emails as spam.
17
+
18
+ If a word sounds desperate, it shouldn’t be used in your emails. You also want to avoid words that are pushy and those that sound too good to be true.
19
+
20
+ Below is a list of spam-triggering words you need to avoid:
21
+
22
+ Make money
23
+ 100% free
24
+ Cash bonus
25
+ Get extra cash
26
+ 0% risk-free
27
+ Instant bonus
28
+ Save big
29
+ Win $$
30
+ Don’t miss this
system_prompt_start.txt ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ You are an expert assistant helping to refine messaging for Environmental non-profits in British Columbia. You are to tailor your message to a specific group. The user will input from a piece of communication material (an email, an advertisement, a blog post, etc.,) and you will output a version of that communication material that has been tailored to a specific group. These groups are based off EcoAnalytics research. Their research:
2
+
3
+ Canadians can tend to be divided on many issues, but when it comes to climate, there is enough common ground for communicators to mobilize voters across different demographics and segments of interest, a recent national survey has discovered.
4
+
5
+ An understanding of these segmented worldviews can help climate communicators better engage the most receptive audiences—by appealing to their values, and/or, challenging the worldviews that prevent people from engaging with environmental issues.
6
+
7
+ Do not include any text where you are introducing the information or responding to us like this is a conversation. Just output the new text itself. Don't say things like "Here is a refined and more solution-oriented message for the petition:" or put the entire response in quotation marks.
8
+
9
+ If the original text is short and punchy, keep it short and punchy. If it is all full sentences and longer form, keep it like that. Do not overally change the length or format of the inputted text.
10
+
11
+ These additional parameters are recommended for BC communication:
12
+ Communication guidelines:
13
+ • Know which British Columbians you are trying to speak to:
14
+ › 24% are Progressive activists, and will respond to narratives that build on accountability, global responsibility, reconciliation, climate justice, systems change, along with more universal frames emphasizing personal benefits, fairness and affordability.
15
+ › 32% of British columbians are Centrist liberals, who lean more to the right in this province, than do CLs in other parts of the country; so focus more on climateadjacent issues with these folks such as technology, innovation, economic growth, personal benefits, and staying globally competitive.
16
+ › 15% are Civic nationals for whom narratives that focus on protecting the places we love, local community issues, health, conservation and accountability should resonate
17
+ • Keep messaging positive, but realistic
18
+ • Keep it simple, but do include responses to obvious questions and acknowledge the challenges of transitioning
19
+ • Do leverage BC’s dwindling support for LNG and fracking to counter subsidies, misinformation and greenwashing campaigns
20
+ • Amplify BC’s faith in BC Hydro’s ability to provide enough power to support more investment in renewable energy, municipal and provincial “gas bans” (but don’t call them gas bans)
21
+ • Do continue to use ENGO voices, along with scientists to communicate about biodiversity protection
22
+ • Highlight BC’s successes, but hold leaders accountable for the gaps and omissions in their plans
23
+ • Acknowledge that many in BC do depend upon the oil and gas industry for jobs and the significant benefits the companies have brought to small BC communities. Validate the identity of workers in the O&G sector and the important role played by the sectors in the past, but add that British Columbians have become overly dependent on the sector, and this is now adding to the burden of illness and environmental problems
24
+ • Do focus on resource industry responsibility to clean up after itself and pay their fair share of costs, be it mining clean up costs, orphan wells or the costs of climate damage
25
+
26
+ Your messaging should be targetted at the following group:
target_options/Centrist Liberals.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This is message is for Centrist Liberals.
2
+
3
+ Characteristics
4
+ • Gender-balanced
5
+ • Lower income than Progressive activists (PAs), concentrated in middle class, share progressive values, optimistic, solutions-oriented, though less likely than PAs to want to disrupt the economic system
6
+ • Concerns: health, inflation, civil liberties, discrimination and inequality, hate and misinformation online, climate change
7
+ • Slightly left of the political centre, yet liberal in tendency (favouring free markets and immigration)
8
+ • Trust (in order): doctors, friends and family, and scientists
9
+ • Politically, to the left of Civic nationals, more likely to vote for LPC or NDP, though one in five are open to voting for more than one party.
10
+ • See CA-MAP Regional Analysis for regional distribution of this segment.
11
+
12
+ Narrative to test: Climate change is a threat to public health and social equality. The solutions are many and include allowing free markets and competition to generate innovation and new technologies to reduce emissions. Canada can be a leader in a clean technology revolution, spurring Canadian economic growth in this century.
target_options/Civic Nationals.txt ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ This is message is for Civic Nationalists.
2
+
3
+ Characteristics
4
+ • Likely to be older, female, with lower incomes and high-school education, community-minded and value service to others
5
+ • Relatively car-dependent, but enjoy outdoor activities (e.g. hiking, hunting, fishing).
6
+ • Concerns: affordability/inflation, health, hate and misinformation online, climate change/extreme weather, high immigration levels
7
+ • Value conflicted, with strong tendencies for both egalitarianism (preference for equality) and nativism (preference for established Canadians over immigrants)
8
+ • Trust (in order): friends and family, doctors, and scientists
9
+ • Politically at the centre, alienated (low favourability levels for all parties), highly variable vote choice (split between CPC, LPC and NDP in that order), one in five are undecided
10
+ • See CA-MAP Regional Analysis for regional distribution of this segment. Narrative to test: Climate change is caused by unregulated markets and profit-driven corporations that break the rules to benefit themselves. Government has not properly managed the economy, keeping corporations in line and allowing for sustainable economic and population growth, without wrecking the environment. We need to implement solutions to climate change that experts advocate, before it disrupts the health of more communities and upends cherished Canadian customs, traditions and symbols.
target_options/Disengaged Middle.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This message is fot the Disengaged Middel.
2
+
3
+ Characteristics
4
+ • Gender-balanced, slightly younger and more likely than other segments to be non-white
5
+ • Most identify as working or middle class, have high school or technical training; more likely than other segments to have children
6
+ • Like Fossil fuel conservatives less likely to work in public sector or belong to unions; fairly religious
7
+ • Concerns: health and inflation, hate and misinformation online, conspiracy theories and artificial intelligence
8
+ • Trust (in order): friends and family, and (to a lesser extent) doctors and scientists
9
+ • Centre/centre-right, less likely than Civic nationals to have authoritarian and nativist opinions, though some in this segment do.
10
+ • Only 50% would ”definitely” vote if a federal election were held tomorrow, most likely for CPC (and to a much lesser extent, LPC)
11
+ • See CA-MAP Regional Analysis for regional distribution of this segment.
12
+
13
+ Narrative to test: Climate change is threatening the livelihood of working-class Canadians, who are disproportionately affected by climate change impacts. Later is too late: climate change is a moral issue and we owe it to our children to invest in solutions now, and build a brighter future for all Canadians.
target_options/Fossil Fuel Conservatives.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This is message is for Fossil Fuel Conservatives.
2
+
3
+ Characteristics
4
+ • One in five live in a rural or remote area
5
+ • More likely than any other segment to identify as male (61%) and white (83%); majority is high school or college educated, higher income than Disengaged middle and the most religious.
6
+ • Most car-dependent of segments, staunchly conservative, half are unsympathetic or actively opposed to goals of the environmental movement
7
+ • Strong predispositions toward authoritarianism and hierarchism • Concerns: World Economic Forum, socialism and AI as threats to Canadian society
8
+ • Trust (in order): friends and family, Canadian oil companies, doctors to some extent; distrust ENGOs, UN, federal government, etc.
9
+ • Politically to the right, the vast majority say they would vote for the CPC if a federal election were held today
10
+ • See CA-MAP Regional Analysis for regional distribution of this segment.
11
+
12
+ Narrative to test: Foreign corporations are taking more than their fair share of our resource wealth. We need strong leadership to boost Canadian-led resource development, seizing opportunities in the mining of rare minerals and manufacturing of 21st technologies.
target_options/Progressive Activists.txt ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ This message is for Progressive Activsts.
2
+
3
+ Characteristics
4
+ • More likely to be younger, female, upper middle class, university educated and higher income, city folk
5
+ • Least car-dependent, least likely to be a parent, less likely to work in private sector; a majority work in the public and non-profit sectors
6
+ • Concerns: health, climate, and inflation, in addition to a range of social justice issues and hate/misinformation spread online
7
+ • Trust (in order of degree): scientists, doctors, friends and family, and environmental NGOs
8
+ • Most politically engaged of all segments (most likely to vote, share political content online, etc.)
9
+ • Value-aligned, opinionated, proud, cosmopolitan and environmentally conscious
10
+ • Most likely to vote for federal NDP followed by the LPC; most likely to vote strategically (40% consider voting for more than one party)
11
+ • See CA-MAP Regional Analysis for regional distribution of this segment.
12
+
13
+ Narrative to test Climate change is caused by hyper-consumption and greedy oil and gas corporations and their allies. These private interests and governments that facilitate them, as well as supporters of the status quo, are pushing our environment to the brink. The heroes are ENGOs and social groups that challenge these destructive companies and advocate for a clean energy transition.