-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.py
275 lines (230 loc) · 10.6 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
import streamlit as st
from openai_service import generate_text
from templates import system_roles
from docx import Document
def append_section_history(section, content):
"""Append to the global chat history"""
st.session_state.section_history[section].append(content)
def populate_section_history(sections):
"""Popualte the section history with the keys recieved, and default to empty list"""
for section in sections:
if section not in st.session_state.section_history:
st.session_state.section_history[section] = []
def get_section_history(section):
"""Get the section history"""
section_history = st.session_state.section_history[section]
# Combine the chat history into a single string
section_history_string = ""
for item in section_history:
section_history_string += item + "\n\n"
return section_history_string
def append_history(role, content):
"""Append to the global chat history"""
st.session_state.chat_history.append({"role": role, "content": content})
def clear_history():
"""Clear the global chat history"""
st.session_state.chat_history = []
# Main App
def main():
# Set the CSS style for the app
if "selected_subtitle" not in st.session_state:
st.session_state.selected_subtitle = ""
if "chat_history" not in st.session_state:
st.session_state.chat_history = []
if "section_history" not in st.session_state:
st.session_state.section_history = {}
st.markdown(f'<style>{open("styles.css").read()}</style>', unsafe_allow_html=True)
# Initialize the session state
if "page" not in st.session_state:
st.session_state.page = "Home"
st.session_state.generated_texts = []
# Home page
if st.session_state.page == "Home":
# Center align the title and information on the home page
st.markdown(
"<h1 style='text-align: center;'>Doc Engine</h1>", unsafe_allow_html=True
)
st.markdown(
"<h5 style='text-align: center;'>Welcome to Doc Engine. This app will help you generate documents faster than ever using AI. Choose the type of document you want to generate and enter the prompts. The AI will generate the rest of the document for you. The goal of Doc Engine is to help you generate the first draft of your document faster so you can spend more time on the more important content.</h5>",
unsafe_allow_html=True,
)
# Get started button
if st.button("Get Started"):
st.session_state.page = "Options"
st.experimental_rerun()
elif st.session_state.page == "Options":
options_page()
elif st.session_state.page == "Generate Text":
generate_text_section()
# Sidebar
# Home button
if st.session_state.page != "Home":
home_button()
# Mode Selection
if st.session_state.page == "Generate Text":
st.sidebar.subheader("Mode Selection")
temperature_modes = {"Creative": 1.5, "Neutral": 1.0, "Precise": 0.0}
selected_mode = st.sidebar.selectbox(
"Select a mode for the prompt:", list(temperature_modes.keys())
)
temperature = temperature_modes[selected_mode]
# Max Word Selection
if st.session_state.page == "Generate Text":
st.sidebar.subheader("Max Words for Output")
max_words: int = st.sidebar.slider(
"Select the approximate maximum number of words for the output:",
50,
1000,
200,
50,
)
# Insert API Key
if st.session_state.page == "Home":
st.sidebar.subheader(" API Key")
api_key = st.sidebar.text_input(
"Enter your Openai API Key here:", type="password"
)
# Save api key to session storage
st.session_state.api_key = api_key
# Export to Word
if st.session_state.page == "Generate Text":
st.sidebar.subheader("Export to Word")
if st.sidebar.button("Export to Word", key="export_to_word"):
if not st.session_state.section_history[st.session_state.selected_subtitle]:
st.warning("Please generate a text section first.")
st.stop()
# Create a new Word document
document = Document()
# Add the generated texts to the Word document
for text in st.session_state.section_history[
st.session_state.selected_subtitle
]:
document.add_paragraph(text)
# Save the Word document
document.save("generated_document.docx")
with open("generated_document.docx", "rb") as f:
st.sidebar.download_button("Download word document ", f, mime="docx")
# About
sidebar()
def generate_text_section():
if "document_type" not in st.session_state:
# If document type is not selected, show a warning message
st.warning("Please select a document type on the 'Options' page.")
st.stop()
generated_text = ""
document_type = st.session_state.document_type
# Get the role template for the selected document type
document_type_system_role = system_roles[document_type]
st.markdown(f"## Template for {document_type}:")
subtitle_list = list(document_type_system_role.keys())
if not st.session_state.section_history:
print("Populating section history")
populate_section_history(subtitle_list)
selected_subtitle = st.selectbox("Select a subtitle:", subtitle_list)
st.session_state.selected_subtitle = selected_subtitle
system_role = document_type_system_role[selected_subtitle]
# Display the template
key = f"prompt_{selected_subtitle.replace(' ', '_')}"
placeholder = f"Enter your prompt for {selected_subtitle} here"
user_input = st.text_area(
label="", value="", placeholder=placeholder, key=key, height=100
)
generate_key = f"generate_{selected_subtitle}"
if st.button("Generate", key=generate_key):
if user_input:
# Combine the template prompt with the user's prompt
prompt = (
f"You will write {selected_subtitle} for a {document_type} with the following in mind:"
+ "\n"
+ user_input
)
generated_text = generate_text(
system_role,
prompt,
)
append_history("user", prompt)
append_history("system", generated_text)
append_section_history(selected_subtitle, generated_text)
print(st.session_state.section_history)
else:
st.warning("Please enter a prompt.")
# Display the generated texts
if (
st.session_state.chat_history
and st.session_state.section_history[selected_subtitle]
):
st.markdown("### Generated Texts:")
st.write(get_section_history(selected_subtitle))
# Delete button
if st.button("Delete All"):
print(st.session_state.chat_history)
if st.session_state.generated_texts:
delete_confirmation = st.warning(
"Are you sure you want to delete all the generated texts?"
)
if delete_confirmation.button("Confirm"):
clear_history()
def options_page():
st.markdown("<h1 style='text-align: center;'>Options</h1>", unsafe_allow_html=True)
st.markdown(
"<h5 style='text-align: center;'> You can now choose two different methods to generate your document. You can either choose a template and enter the prompts for each subtitle, or you can upload the whole case description and make prompts with more freely without the subtitle restrictions. </h5>",
unsafe_allow_html=True,
)
# Document Options
if st.session_state.page == "Options":
st.header("Document Options")
document_type = st.selectbox(
"Choose the type of documentation:", list(system_roles.keys())
)
# Template Options
if st.button("Go to template"):
# Store the selected document type in the session state
st.session_state.document_type = document_type
st.session_state.page = "Generate Text"
st.experimental_rerun()
def sidebar():
st.sidebar.header("About")
st.sidebar.write(
"Doc Engine is developed using Streamlit and OpenAI's GPT-3 model. It aims to simplify the document generation process and save time by automating the initial drafting phase."
)
# How to Use
st.sidebar.header("How to Use")
st.sidebar.write("1. Select the type of document you want to generate.")
st.sidebar.write(
"2. Make sure the mode and maximum words for output are set to your preference."
)
st.sidebar.write(
"3. Enter your prompt in the text box below the template and press the 'Generate' button."
)
st.sidebar.write("4. Review the generated text and regenerate if necessary.")
st.sidebar.write(
"5. Use the 'Export to Word' button to export the generated text to a Word document. You find it at the bottom of the sidebar."
)
# FAQ
st.sidebar.header("FAQ")
st.sidebar.write("What is Doc Engine?")
st.sidebar.write(
"Doc Engine is an AI-powered app that helps you generate documents by providing prompts and generating the rest of the content using OpenAI's GPT-3 model."
)
st.sidebar.write("Can I trust the generated text 100%?")
st.sidebar.write(
"No. The generated text is meant to be used as a starting point for your document. You should always review the generated text and make any necessary changes to ensure the accuracy of the content."
)
st.sidebar.write("How do I use the mode selection?")
st.sidebar.write(
"The mode selection allows you to choose the tone of the generated text. The 'Creative' mode will generate more creative text, while the 'Precise' mode will generate more precise text. The 'Neutral' mode is a balance between the two."
)
st.sidebar.write("How do I use the maximum words for output selection?")
st.sidebar.write(
"The maximum words for output selection allows you to choose the approximate maximum number of words for the generated text. The actual number of words may be slightly higher or lower than the selected number since the model actually generates tokens instead of words."
)
st.sidebar.write("Where will the exported Word document be saved?")
st.sidebar.write(
"The exported Word document will be saved in your Downloads folder."
)
def home_button():
if st.sidebar.button("Home"):
st.session_state.page = "Home"
st.experimental_rerun()
if __name__ == "__main__":
main()