- Notifications
You must be signed in to change notification settings - Fork2
/
Copy pathapp.py
336 lines (271 loc) · 12.5 KB
/
app.py
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
importstreamlitasst
fromopenaiimportOpenAI
fromopenaiimportAzureOpenAI
importjson
importuuid
importre
importitertools
fromtypingimportDict,List,Optional,Union
fromdatetimeimportdatetime
frompymongo.mongo_clientimportMongoClient
frompymongo.server_apiimportServerApi
__name__="RogueGPT"
__version__="1.0.0"
__author__="Alexander Loth"
__email__="Alexander.Loth@microsoft.com"
__research_paper__="https://arxiv.org/abs/2404.03021"
__report_a_bug__="https://github.com/aloth/RogueGPT/issues"
# Constants
CONFIG_FILE='prompt_engine.json'
defgenerate_fragment(prompt:str,base_url:str,api_key:str,api_type:str,api_version:str=None,model:str=None)->str:
"""
Generates a news fragment using OpenAI's or Azure OpenAI's GPT model and returns the generated response.
Args:
prompt (str): The prompt to generate the news fragment.
base_url (str): The base URL for the OpenAI or Azure OpenAI API.
api_key (str): The API key for authentication.
api_type (str): Specifies the type of API, either 'OpenAI' or 'AzureOpenAI'.
api_version (str, optional): The API version (only needed for Azure OpenAI). Defaults to None.
model (str, optional): The model identifier for the GPT model (e.g., 'gpt-4'). Defaults to None.
Returns:
str: The generated response from the model.
Raises:
ValueError: If an invalid API type is provided.
"""
# Initialize the client based on the API type (OpenAI or AzureOpenAI)
ifapi_type=="OpenAI":
client=OpenAI(
base_url=base_url,
api_key=api_key
)
elifapi_type=="AzureOpenAI":
client=AzureOpenAI(
api_key=api_key,
api_version=api_version,
azure_endpoint=base_url
)
else:
raiseValueError("Invalid API type. Must be either 'OpenAI' or 'AzureOpenAI'.")
# Create a streaming completion request with the provided prompt and model
stream=client.chat.completions.create(
model=model,
messages= [{"role":"user","content":prompt}],
stream=True
)
# Process and return the streamed response
generated_response=st.write_stream(stream)
returngenerated_response
defsave_fragment(fragment:dict)->None:
"""
Saves a news fragment to the MongoDB database.
Args:
fragment (dict): The news fragment to be saved.
Raises:
Exception: If there's an error while saving the fragment to the database.
"""
try:
withMongoClient(st.secrets["mongo"]["connection"],server_api=ServerApi('1'))asclient:
db=client.realorfake
collection=db.fragments
collection.insert_one(fragment)
st.success("Fragment saved successfully.")
exceptExceptionase:
st.error(f"Error saving fragment:{str(e)}")
defrender_ui(component_dict:dict,key_prefix:str="")->dict:
"""
Dynamically renders UI components based on the configuration provided in the components dictionary.
Args:
component_dict (dict): A dictionary containing the UI components configuration.
key_prefix (str): A prefix added to the keys to ensure uniqueness (useful in recursion).
Returns:
dict: A dictionary of user selections for each component.
"""
user_selections= {}
forkey,valueincomponent_dict.items():
ifisinstance(value,dict):# If the value is a nested dict, use a selectbox for top-level selection
selected_option=st.selectbox(f'Choose{key}',list(value.keys()))
user_selections[key]=selected_option
# Based on the selected option, render the nested component (e.g., Styles)
nested_dict=value[selected_option]
fornested_key,nested_valueinnested_dict.items():
ifisinstance(nested_value,list):# Render multiselect for nested lists
selected_nested_options=st.multiselect(f'Choose{nested_key}',nested_value,default=nested_value)
user_selections[f"{nested_key}"]=selected_nested_options
elifisinstance(value,list):# For top-level lists, use multiselect
selected_options=st.multiselect(f'Choose{key}',value,default=value)
user_selections[key]=selected_options
returnuser_selections
defcollect_keys(component_dict:dict,collected_keys:list= [])->list:
"""
Recursively collects all keys from nested dictionaries.
Args:
component_dict (dict): The dictionary to collect keys from.
collected_keys (list, optional): A list to store collected keys. Defaults to an empty list.
Returns:
list: A list of all collected keys.
"""
forkey,valueincomponent_dict.items():
collected_keys.append(key)
ifisinstance(value,dict):
forsub_keyinvalue.keys():
collect_keys(value[sub_key],collected_keys)
returncollected_keys
deffix_structure(selections:dict)->dict:
"""
Ensures all selections are in list form.
Args:
selections (dict): A dictionary of user selections.
Returns:
dict: A dictionary with all values converted to lists.
"""
corrected_selections= {}
forkey,valueinselections.items():
ifisinstance(value,list):# If the value is already a list, use it as is
corrected_selections[key]=value
else:# Treat single strings as a list with a single element
corrected_selections[key]= [value]
returncorrected_selections
defmanual_data_entry_ui()->None:
"""
Renders UI for manual data entry of news fragments.
This function doesn't return anything but updates the Streamlit UI.
"""
fragment_id=uuid.uuid4().hex
st.header("Input News Details")
# Automatically generated FragmentID (display only, no input from user)
st.text_input("Fragment ID",value=fragment_id,disabled=True)
# Other details with user input
content=st.text_area("Content")
origin=st.selectbox("Origin", ["Human","Machine"])
iforigin=="Human":
human_outlet=st.text_input("Publishing Outlet Name")
human_url=st.text_input("URL of News Source")
machine_model=""
machine_prompt=""
else:
human_outlet=""
human_url=""
machine_model=st.text_input("Generative AI Model")
machine_prompt=st.text_area("Prompt")
language=st.selectbox("Language", ["en","de","fr","es"])
is_fake=st.checkbox("Is this fake news?")
creation_date=datetime.today()
# Button to submit and save the input data
submit_button=st.button("Submit")
ifsubmit_button:
# Process the submitted data (for demonstration, just display it)
st.write(f"Fragment ID:{fragment_id}")
st.write(f"Content:{content}")
st.write(f"Origin:{origin}")
st.write(f"Publishing Outlet Name:{human_outlet}")
st.write(f"URL of News Source:{human_url}")
st.write(f"Generative AI Model:{machine_model}")
st.write(f"Prompt:{machine_prompt}")
st.write(f"Language:{language}")
st.write(f"Is Fake:{is_fake}")
st.write(f"Creation Date:{creation_date}")
fragment= {
"FragmentID":fragment_id,
"Content":content,
"Origin":origin,
"HumanOutlet":human_outlet,
"HumanURL":human_url,
"MachineModel":machine_model,
"MachinePrompt":machine_prompt,
"ISOLanguage":language,
"IsFake":is_fake,
"CreationDate":creation_date
}
save_fragment(fragment)
st.rerun()
defautomatic_news_generation_ui()->None:
"""
Renders UI for automatic news generation and handles the logic for generating news fragments.
This function doesn't return anything but updates the Streamlit UI and generates news fragments.
"""
st.header("Automatic News Generation")
st.subheader("Prompt")
# Function to load JSON data
defload_json(filename):
withopen(filename,'r')asf:
returnjson.load(f)
# Load the JSON structure
data=load_json(CONFIG_FILE)
prompt_template=data["PromptTemplate"]
generator_url=data["GeneratorURL"]
generator_api_key=data["GeneratorAPIKey"]
generator_api_type=data["GeneratorAPIType"]
generator_api_version=data["GeneratorAPIVersion"]
generator_model=data["GeneratorModel"]
components=data["Components"]
all_possible_keys=collect_keys(components)
# Identifying placeholders including nested ones
placeholders=re.findall(r"\[\[(.*?)\]\]",prompt_template)
uncovered_placeholders= [phforphinplaceholdersifphnotinall_possible_keys]
# User inputs for PromptTemplate, GeneratorServerURL, and GeneratorModel
user_prompt_template=st.text_input("Prompt Template",prompt_template)
# Render UI components based on JSON and collect selections
user_selections=render_ui(components)
# Find placeholders in the template that are not covered in the JSON
forplaceholderinuncovered_placeholders:
user_input=st.text_area(f"Enter values for{placeholder} (each line is a value)",key=f"placeholder_{placeholder}")
# Splitting by newlines to get options array
user_input_options=user_input.split("\n")
user_selections[placeholder]=user_input_options
# Initialize prompt with the template
prompt=prompt_template
# Replace placeholders in the template with user selections
forplaceholder,selectionsinuser_selections.items():
placeholder_key=f"[[{placeholder}]]"
# Use the first selection if available
selection_text=selections[0]ifisinstance(selections,list)andselectionselseselections
prompt=prompt.replace(placeholder_key,selection_text)
# Display the generated prompt
st.write("Prompt Preview:",prompt)
st.subheader("Generator")
user_generator_url=st.text_input("Generator URL",generator_url)
user_generator_api_key=st.text_input("Generator API Key",generator_api_key)
user_generator_api_type=st.selectbox("Generator API Type",generator_api_type)
user_generator_api_version=st.selectbox("Generator API Version",generator_api_version)
user_generator_model=st.selectbox("Generator Model",generator_model)
st.subheader("Meta data")
user_is_fakenews=st.checkbox("Mark this as fake news?")
ifst.button("Generate"):
# Create all combinations of the selected options
iter_selections=fix_structure(user_selections)
st.write(iter_selections)
keys,values=zip(*iter_selections.items())
combinations= [dict(zip(keys,v))forvinitertools.product(*values)]
# Generate and display prompts for each combination
fori,combinationinenumerate(combinations):
prompt_filled=prompt_template
forkey,valueincombination.items():
prompt_filled=prompt_filled.replace(f"[[{key}]]",value)
st.write("Using prompt: ",prompt_filled)
generated_fragment=generate_fragment(
prompt=prompt_filled,
base_url=user_generator_url,
api_key=user_generator_api_key,
api_type=user_generator_api_type,
api_version=user_generator_api_version,
model=user_generator_model
)
combination["FragmentID"]=uuid.uuid4().hex
combination["Content"]=generated_fragment
combination["Origin"]="Machine"
combination["MachineModel"]=user_generator_model
combination["MachinePrompt"]=prompt_filled
combination["IsFake"]=user_is_fakenews
combination["CreationDate"]=datetime.today()
save_fragment(combination)
# Add a separator for clarity between prompts
st.markdown("---")
# UI to input news fragment details
st.title("RogueGPT: News Ingestion")
st.markdown("*Disclaimer:* [RogueGPT](https://github.com/aloth/RogueGPT/) is part of the [JudgeGPT research project](https://github.com/aloth/JudgeGPT/).")
st.markdown("Learn more about the impact of Generative AI on fake news through our [open access paper]("+__research_paper__+").")
tab_generaor,tab_manual=st.tabs(["Generator","Manual Data Entry"])
withtab_generaor:
automatic_news_generation_ui()
withtab_manual:
manual_data_entry_ui()