OrganizingForChange commited on
Commit
7346450
·
verified ·
1 Parent(s): cb1918e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +46 -20
app.py CHANGED
@@ -1,7 +1,6 @@
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:
@@ -14,6 +13,8 @@ REGION_OPTIONS_DIR = "region_options"
14
 
15
  def get_region_options():
16
  options = []
 
 
17
  for filename in os.listdir(REGION_OPTIONS_DIR):
18
  if filename.endswith(".txt"):
19
  options.append(filename[:-4])
@@ -30,6 +31,8 @@ def get_region_prompt(region_name):
30
 
31
  def get_target_options():
32
  options = []
 
 
33
  for filename in os.listdir(TARGET_OPTIONS_DIR):
34
  if filename.endswith(".txt"):
35
  options.append(filename[:-4])
@@ -51,7 +54,6 @@ def compose_system_prompt(targets, additional_sysinfo, feedback, user_message, r
51
 
52
  prompt = f"{SYSTEM_PROMPT_START}\n"
53
 
54
- # Insert region context if present, with explicit instructions
55
  if region:
56
  region_prompt = get_region_prompt(region)
57
  if region_prompt.strip():
@@ -64,14 +66,12 @@ def compose_system_prompt(targets, additional_sysinfo, feedback, user_message, r
64
  "If you are also generating feedback, explicitly include a section that describes how the message was adapted for the {region} regional context."
65
  )
66
 
67
- # Audience segment context continues unchanged...
68
  prompt += (
69
  f"\nThe message below is intended for the following combined audience segments: "
70
  f"{', '.join(targets)}. Please address the message to all these groups together, synthesizing messaging approaches to be clear, relevant, and persuasive for the group as a whole. "
71
  "When there may be conflicting messaging advice for different segments, please use your best judgment to combine or balance them."
72
  )
73
 
74
- # Add full prompt context for each checked segment
75
  for t in targets:
76
  p = get_target_prompt(t)
77
  if p.strip():
@@ -79,22 +79,42 @@ def compose_system_prompt(targets, additional_sysinfo, feedback, user_message, r
79
 
80
  if additional_sysinfo and additional_sysinfo.strip():
81
  prompt += "\n" + additional_sysinfo.strip() + "\n"
 
82
  prompt += length_instruction
 
83
  if feedback:
84
  prompt += SYSTEM_PROMPT_FEEDBACK
85
  return prompt.strip()
86
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
87
  def run_llm(
88
- api_key, targets, feedback, additional_sysinfo, user_message, region, model, temperature, top_p
89
  ):
 
 
90
  try:
91
  client = openai.OpenAI(api_key=api_key)
92
  except Exception as e:
93
- return f"Could not initialize OpenAI client: {e}", ""
94
 
95
  prompt = compose_system_prompt(targets, additional_sysinfo, feedback, user_message, region)
96
  if prompt.startswith("Error:"):
97
- return prompt, ""
98
 
99
  try:
100
  completion = client.chat.completions.create(
@@ -114,9 +134,16 @@ def run_llm(
114
  token_message = f"Prompt: {prompt_tokens}, Completion: {completion_tokens}, Total: {total_tokens} | Temp: {temperature} | Top-p: {top_p} | {model}"
115
  else:
116
  token_message = f"Token info unavailable | Temp: {temperature} | Top-p: {top_p} | {model}"
117
- return completion.choices[0].message.content.strip(), token_message
 
 
 
 
 
 
 
118
  except Exception as e:
119
- return f"An error occurred: {e}", ""
120
 
121
  target_options = get_target_options()
122
  model_choices = ["gpt-4.1", "gpt-4", "gpt-3.5-turbo"]
@@ -132,7 +159,7 @@ This tool helps you improve, adapt, and review your written messaging—emails,
132
 
133
  You can select your intended audiences (choose multiple if needed!), add optional instructions for the AI, and receive an output that is tailored for clarity, effectiveness, and your communication goal.
134
 
135
- 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 ('---').
136
 
137
  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.
138
 
@@ -199,13 +226,7 @@ This tool was created by [Organizing for Change](https://www.organizingforchange
199
  choices=target_options,
200
  label="Target Audience Segments",
201
  info="Select one or more intended audience segments. Your message will be adapted for all selected groups together.",
202
- value=[], # default: nothing checked
203
- )
204
- with gr.Row():
205
- feedback = gr.Checkbox(
206
- label="Request Feedback from LLM?",
207
- info="If checked, the LLM will provide additional feedback and suggestions about your message after rewriting it.",
208
- value=True # This makes it checked by default!
209
  )
210
 
211
  additional_sysinfo = gr.Textbox(
@@ -229,6 +250,11 @@ This tool was created by [Organizing for Change](https://www.organizingforchange
229
  label="Message as Modified by LLM for Target Audience(s)",
230
  info="The LLM’s refined response will appear here. You can regenerate the response and get something new by clicking 'Generate Targetted Message' again."
231
  )
 
 
 
 
 
232
  with gr.Row():
233
  token_count_box = gr.Textbox(
234
  label="Token Usage",
@@ -243,9 +269,9 @@ This tool was created by [Organizing for Change](https://www.organizingforchange
243
  # --- Connect submit button after outputs are created ---
244
  submit.click(
245
  fn=run_llm,
246
- inputs=[api_key, target, feedback, additional_sysinfo, user_message, region, model, temperature, top_p],
247
- outputs=[output, token_count_box]
248
  )
249
 
250
  if __name__ == "__main__":
251
- demo.launch(share=True)
 
1
  import gradio as gr
2
  import openai
3
  import os
 
4
 
5
  def read_file(path):
6
  with open(path, "r", encoding="utf-8") as f:
 
13
 
14
  def get_region_options():
15
  options = []
16
+ if not os.path.isdir(REGION_OPTIONS_DIR):
17
+ return options
18
  for filename in os.listdir(REGION_OPTIONS_DIR):
19
  if filename.endswith(".txt"):
20
  options.append(filename[:-4])
 
31
 
32
  def get_target_options():
33
  options = []
34
+ if not os.path.isdir(TARGET_OPTIONS_DIR):
35
+ return options
36
  for filename in os.listdir(TARGET_OPTIONS_DIR):
37
  if filename.endswith(".txt"):
38
  options.append(filename[:-4])
 
54
 
55
  prompt = f"{SYSTEM_PROMPT_START}\n"
56
 
 
57
  if region:
58
  region_prompt = get_region_prompt(region)
59
  if region_prompt.strip():
 
66
  "If you are also generating feedback, explicitly include a section that describes how the message was adapted for the {region} regional context."
67
  )
68
 
 
69
  prompt += (
70
  f"\nThe message below is intended for the following combined audience segments: "
71
  f"{', '.join(targets)}. Please address the message to all these groups together, synthesizing messaging approaches to be clear, relevant, and persuasive for the group as a whole. "
72
  "When there may be conflicting messaging advice for different segments, please use your best judgment to combine or balance them."
73
  )
74
 
 
75
  for t in targets:
76
  p = get_target_prompt(t)
77
  if p.strip():
 
79
 
80
  if additional_sysinfo and additional_sysinfo.strip():
81
  prompt += "\n" + additional_sysinfo.strip() + "\n"
82
+
83
  prompt += length_instruction
84
+
85
  if feedback:
86
  prompt += SYSTEM_PROMPT_FEEDBACK
87
  return prompt.strip()
88
 
89
+ def split_main_and_feedback(llm_output):
90
+ """
91
+ Splits the LLM output at the first appearance of a '---' that is surely meant as a feedback divider.
92
+ """
93
+ import re
94
+ # Split at first '---' line
95
+ m = re.search(r'(?:^|\n)---(?:\n|$)', llm_output)
96
+ if m:
97
+ idx = m.start()
98
+ main_message = llm_output[:idx].strip()
99
+ feedback_message = llm_output[m.end():].strip()
100
+ else:
101
+ main_message = llm_output.strip()
102
+ feedback_message = ""
103
+ return main_message, feedback_message
104
+
105
  def run_llm(
106
+ api_key, targets, additional_sysinfo, user_message, region, model, temperature, top_p
107
  ):
108
+ feedback = True # ALWAYS ENABLED
109
+
110
  try:
111
  client = openai.OpenAI(api_key=api_key)
112
  except Exception as e:
113
+ return f"Could not initialize OpenAI client: {e}", "", ""
114
 
115
  prompt = compose_system_prompt(targets, additional_sysinfo, feedback, user_message, region)
116
  if prompt.startswith("Error:"):
117
+ return prompt, "", ""
118
 
119
  try:
120
  completion = client.chat.completions.create(
 
134
  token_message = f"Prompt: {prompt_tokens}, Completion: {completion_tokens}, Total: {total_tokens} | Temp: {temperature} | Top-p: {top_p} | {model}"
135
  else:
136
  token_message = f"Token info unavailable | Temp: {temperature} | Top-p: {top_p} | {model}"
137
+
138
+ full_content = completion.choices[0].message.content.strip()
139
+ main_msg, feedback_msg = split_main_and_feedback(full_content)
140
+ if not feedback_msg:
141
+ feedback_msg = "(No feedback section found. The model may not have followed instructions.)"
142
+
143
+ return main_msg, feedback_msg, token_message
144
+
145
  except Exception as e:
146
+ return f"An error occurred: {e}", "", ""
147
 
148
  target_options = get_target_options()
149
  model_choices = ["gpt-4.1", "gpt-4", "gpt-3.5-turbo"]
 
159
 
160
  You can select your intended audiences (choose multiple if needed!), add optional instructions for the AI, and receive an output that is tailored for clarity, effectiveness, and your communication goal.
161
 
162
+ The system will reformulate your message to match the length of your input (not longer), and you will receive both a rewritten message and additional feedback and suggestions about your message after rewriting it.
163
 
164
  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.
165
 
 
226
  choices=target_options,
227
  label="Target Audience Segments",
228
  info="Select one or more intended audience segments. Your message will be adapted for all selected groups together.",
229
+ value=[] # default: nothing checked
 
 
 
 
 
 
230
  )
231
 
232
  additional_sysinfo = gr.Textbox(
 
250
  label="Message as Modified by LLM for Target Audience(s)",
251
  info="The LLM’s refined response will appear here. You can regenerate the response and get something new by clicking 'Generate Targetted Message' again."
252
  )
253
+ feedback_box = gr.Textbox(
254
+ lines=8,
255
+ label="LLM Feedback",
256
+ info="The LLM’s feedback and suggestions specific to your message and audience will appear here."
257
+ )
258
  with gr.Row():
259
  token_count_box = gr.Textbox(
260
  label="Token Usage",
 
269
  # --- Connect submit button after outputs are created ---
270
  submit.click(
271
  fn=run_llm,
272
+ inputs=[api_key, target, additional_sysinfo, user_message, region, model, temperature, top_p],
273
+ outputs=[output, feedback_box, token_count_box]
274
  )
275
 
276
  if __name__ == "__main__":
277
+ demo.launch(share=True)