Shashank1406 commited on
Commit
256d47f
·
verified ·
1 Parent(s): 4dd2154

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +346 -0
app.py ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ import json
3
+ import base64
4
+
5
+ import streamlit as st
6
+ from langchain.llms import OpenAI
7
+ from langchain import PromptTemplate
8
+ from langchain.chains import LLMChain
9
+ from langchain.llms import OpenAI
10
+ from PyPDF2 import PdfReader
11
+ import streamlit as st
12
+ from streamlit_option_menu import option_menu
13
+ from langchain.text_splitter import CharacterTextSplitter
14
+ from langchain_community.vectorstores import Chroma
15
+ from langchain_community.embeddings import OpenAIEmbeddings
16
+ import pandas as pd
17
+
18
+
19
+ # Initialize session states
20
+ if "generated" not in st.session_state:
21
+ st.session_state["generated"] = []
22
+ if "past" not in st.session_state:
23
+ st.session_state["past"] = []
24
+ if "input" not in st.session_state:
25
+ st.session_state["input"] = ""
26
+ if "vectorstore" not in st.session_state:
27
+ st.session_state["vectorstore"] = None
28
+ if "rfp_details" not in st.session_state:
29
+ st.session_state["rfp_details"] = ""
30
+ if "is_data_processed" not in st.session_state:
31
+ st.session_state["is_data_processed"] = False
32
+
33
+ if "user_stories" not in st.session_state:
34
+ st.session_state["user_stories"] = ""
35
+ if "user_stories_json" not in st.session_state:
36
+ st.session_state["user_stories_json"] = []
37
+ if "is_user_stories_created" not in st.session_state:
38
+ st.session_state["is_user_stories_created"] = False
39
+ if "rfp_summary" not in st.session_state:
40
+ st.session_state["rfp_summary"] = ""
41
+
42
+
43
+ bot_template = """As a highly intelligent and powerful chatbot, your personality is a business analyst's responsibility.
44
+ Your designated name is RFP Bot. Initiate the conversation with a warm greeting only when the user asks something for the first time. Subsequent interactions can skip the greeting.
45
+ Your generated responses should be comprehensive, utilizing pointers when necessary for an enhanced user experience. Provide detailed answers, and if the user's input isn't related to personality, respond politely with an apology, encouraging them to ask questions related to your established personality. Keep your responses concise and accurate, seeking additional information from the user when required.
46
+ Incorporate the provided context and any relevant information from the chat history into your responses. If the user's input is related to the context or question, articulate your answer accordingly.
47
+ {context}
48
+ Human: {input}
49
+ Assistant:"""
50
+
51
+ user_story_template = """Given the project details with the following parameters:
52
+
53
+ **Project Name:** {project_name}
54
+
55
+ **RFP details:**
56
+ {rfp_details}
57
+
58
+ As a business analyst, analyze the given RFP details to delineate epics for the project. Break down the epic into features and features into individual requirements, adhering to the agile software development INVEST principles. Subsequently, generate user stories based fo each requirement. Ensure each story follows the "As a, I want to, So that" format and strictly avoid combining stories together.
59
+
60
+ **Examples**
61
+
62
+ 1. Epic: User Authentication and Account Security Enhancements
63
+
64
+ 1. Feature 1: User Registration
65
+ - Story 1:
66
+ - As a user, I want to provide my basic information, such as name and email address during sign-up, so that the platform can create a personalized account for me.
67
+ - Story 2:
68
+ - As a user, I want the sign-up form to include a CAPTCHA verification step, so that the system can prevent automated bots from creating fake accounts.
69
+ - Story 3:
70
+ - As a user, I want the sign-up form to include optional fields for additional profile information, so that I can customize my account based on my interests.
71
+ - Story 4:
72
+ - As a user, I want the platform to clearly communicate its data usage and privacy policy during the sign-up process, so that I can make an informed decision before creating an account.
73
+
74
+ 2. Feature 2: User Authentication
75
+ - Story 1:
76
+ - As a registered user, I want to log in securely with my credentials, so that I can access personalized account information.
77
+ - Story 2:
78
+ - As a registered user, I want the login page to feature a "Forgot Password" link, so that I can easily initiate the password recovery process if needed.
79
+ - Story 3:
80
+ - As a user concerned about account security, I want the platform to send a notification email whenever my account is accessed from a new device, so that I can be aware of any potential unauthorized access.
81
+ - Story 4:
82
+ - As a returning user, I want the option to enable two-factor authentication (2FA) for an extra layer of security during the login process, so that my account remains protected.
83
+ - Story 5:
84
+ - As a user striving for a seamless experience, I want the platform to offer a "Stay Logged In" option during login, so that I don't have to enter my credentials every time I revisit the site.
85
+ - Story 6:
86
+ - As a user with multiple devices, I want the ability to log out remotely from any active sessions through the account settings, so that I can maintain control over my account access.
87
+
88
+ 3. Feature 3: Account Security Enhancements
89
+ - Story 1:
90
+ - As a security-conscious user, I want the platform to regularly prompt me to update my password and provide guidance on creating a secure password to enhance the overall security of my account.
91
+ - Story 2:
92
+ - As a user who values privacy, I want the platform to automatically log me out after a period of inactivity, ensuring that my account is secure even if I forget to log out manually.
93
+ - Story 3:
94
+ - As a user concerned about account recovery, I want the platform to offer multiple secure account recovery options, such as email verification and phone number verification, to ensure I can regain access to my account if needed.
95
+ """
96
+
97
+ summary_template = """Given the project details with the following parameters:
98
+
99
+ **Project Name:** {project_name}
100
+
101
+ **RFP details:**
102
+ {rfp_details}
103
+
104
+ As a business analyst, analyze the given RFP details and give the detailed summary of the project.
105
+
106
+ """
107
+
108
+ convert_json_template = """
109
+ Given the project user stories:
110
+
111
+ **user_stories:** {user_stories}
112
+
113
+ Create a JSON representation that captures the structure and details of each epic and feature, including their respective stories. Ensure that the JSON format is well-organized, with clear hierarchies for epic,features and stories.
114
+
115
+ Example structure:
116
+
117
+ {json_structure}
118
+ """
119
+
120
+ json_structure = {
121
+ "epics": [
122
+ {
123
+ "name": "App Performance and Efficiency",
124
+ "features": [
125
+ {
126
+ "name": "Fast and Zero Load Time",
127
+ "stories": [
128
+ {
129
+ "name": "Story 1",
130
+ "description": "As a user, I want the app to load quickly with zero load time, so that I can access news content efficiently."
131
+ },
132
+ {
133
+ "name": "Story 2",
134
+ "description": "As a user, I want the installation process of the mobile app to be quick and hassle-free, so that I can start using the app immediately after download without any complications."
135
+ }
136
+ ]
137
+ }
138
+ ]
139
+ }
140
+ ]
141
+ }
142
+
143
+
144
+ def clear_rfp_data():
145
+ st.session_state.clear()
146
+
147
+
148
+ # rfp summary creater
149
+
150
+ summary_prompt = PromptTemplate(
151
+ input_variables=["project_name", "rfp_details"],
152
+ template=summary_template
153
+ )
154
+
155
+ summary_chain = LLMChain(
156
+ llm=OpenAI(model_name='gpt-3.5-turbo-16k', temperature=0.7,
157
+ openai_api_key=''),
158
+ prompt=summary_prompt,
159
+ verbose="true",
160
+ )
161
+
162
+ # process rfp data from pdf file
163
+
164
+
165
+ def process_rfp_data(project_name, file):
166
+ if project_name and file:
167
+ loader = PdfReader(file)
168
+ for i, page in enumerate(loader.pages):
169
+ content = page.extract_text()
170
+ if content:
171
+ temp = st.session_state["rfp_details"]
172
+ st.session_state["rfp_details"] = temp+content
173
+ text_splitter = CharacterTextSplitter(
174
+ separator='\n', chunk_size=1000, chunk_overlap=150, length_function=len)
175
+ texts = text_splitter.split_text(
176
+ st.session_state["rfp_details"])
177
+ st.session_state["vectorstore"] = Chroma().from_texts(texts, embedding=OpenAIEmbeddings(
178
+ openai_api_key=''))
179
+ st.session_state.project_name = project_name
180
+ st.session_state["rfp_summary"] = summary_chain.run(
181
+ {"project_name": st.session_state["project_name"], "rfp_details": st.session_state["rfp_details"]})
182
+ st.session_state["is_data_processed"] = True
183
+ st.success('data processed sucessfully')
184
+
185
+
186
+ # genrate bot conversastion
187
+
188
+ bot_prompt = PromptTemplate(
189
+ input_variables=["context", "input"],
190
+ template=bot_template
191
+ )
192
+
193
+ bot_chain = LLMChain(
194
+ llm=OpenAI(model_name='gpt-3.5-turbo-16k', temperature=0.7,
195
+ openai_api_key=''),
196
+ prompt=bot_prompt,
197
+ verbose="true",
198
+ )
199
+
200
+
201
+ def genrate_bot_result():
202
+ if len(st.session_state["input"]) > 0:
203
+ db = st.session_state["vectorstore"]
204
+ context = db.similarity_search(st.session_state["input"])
205
+ inputs = {
206
+ "context": context[0].page_content,
207
+ "input": st.session_state["input"]
208
+ }
209
+ output = bot_chain.run(inputs)
210
+ st.session_state.past.append(st.session_state["input"])
211
+ st.session_state.generated.append(output)
212
+ st.session_state["input"] = ""
213
+
214
+
215
+ # genrate user stories user_story_template = """
216
+
217
+ user_story_prompt = PromptTemplate(
218
+ input_variables=["project_name", "rfp_details"],
219
+ template=user_story_template
220
+ )
221
+
222
+ user_story_chain = LLMChain(
223
+ llm=OpenAI(model_name='gpt-3.5-turbo-16k', temperature=0.7,
224
+ openai_api_key=''),
225
+ prompt=user_story_prompt,
226
+ verbose="true",
227
+ )
228
+
229
+ # prompt template for json
230
+
231
+ json_prompt_template = PromptTemplate(
232
+ input_variables=["user_stories", "json_structure"],
233
+ template=convert_json_template
234
+ )
235
+
236
+ json_chain = LLMChain(
237
+ llm=OpenAI(model_name='gpt-3.5-turbo-16k', temperature=0.7,
238
+ openai_api_key=''),
239
+ prompt=json_prompt_template,
240
+ verbose="true",
241
+ )
242
+
243
+
244
+ def genrate_user_stories():
245
+ output = user_story_chain.run(
246
+ {"project_name": st.session_state["project_name"], "rfp_details": st.session_state["rfp_details"]})
247
+ st.session_state["user_stories"] = output
248
+
249
+ json_response = json_chain.run(
250
+ {"user_stories": st.session_state["user_stories"], "json_structure": json_structure})
251
+
252
+ user_stories_data = json.loads(json_response)
253
+
254
+ for epic_data in user_stories_data['epics']:
255
+ epic = epic_data["name"]
256
+ for feature_data in epic_data['features']:
257
+ feature = feature_data["name"]
258
+ for story in feature_data["stories"]:
259
+ st.session_state.user_stories_json.append(
260
+ {"epic": epic, "Feature": feature, "Story Description": story["description"]})
261
+ st.session_state["is_user_stories_created"] = True
262
+
263
+
264
+ def genrate_technical_stories():
265
+ print('genrate technical stories calling')
266
+
267
+
268
+ def export_stories():
269
+ data_df = pd.DataFrame(st.session_state["user_stories_json"])
270
+ csv_data = data_df.to_csv(index=False)
271
+ b64 = base64.b64encode(csv_data.encode()).decode()
272
+ href = f'<a href="data:file/csv;base64,{b64}" download="data.csv">Download CSV File</a>'
273
+ st.markdown(href, unsafe_allow_html=True)
274
+ print('generate technical stories calling')
275
+
276
+
277
+ def main():
278
+ if "input" not in st.session_state:
279
+ st.session_state["input"] = ""
280
+
281
+ with st.sidebar:
282
+ menu_choice = option_menu(menu_title="RFPStoryCraft", options=[
283
+ 'Home', 'RFP Bot', 'User Stories', "Summary"], icons=['house','list-task', 'book', 'book'])
284
+ if st.session_state["is_data_processed"] == True:
285
+ st.button('Clear RFP Data', on_click=clear_rfp_data)
286
+
287
+ if menu_choice == 'Home':
288
+ with st.form("my_form"):
289
+ project_name = st.text_input('Project Name', key='Project Name',
290
+ type="default", placeholder='Project Name')
291
+ file = st.file_uploader('Document', type='pdf')
292
+
293
+ submitted = st.form_submit_button("Process Data")
294
+
295
+ if submitted:
296
+ if project_name and file:
297
+ process_rfp_data(project_name, file)
298
+ else:
299
+ st.warning(
300
+ 'project_name and file are required to create create stories', icon="⚠️")
301
+
302
+ if menu_choice == 'RFP Bot':
303
+ if st.session_state["is_data_processed"] == True:
304
+ st.title(" RFP Chatbot ")
305
+ st.subheader(" Powered by Coffeebeans")
306
+ st.text_input("You: ", st.session_state["input"], key="input",
307
+ placeholder="Your AI assistant here! Ask me Queries related to RFP",
308
+ on_change=genrate_bot_result(),
309
+ label_visibility='hidden')
310
+ with st.container():
311
+ for i in range(len(st.session_state['generated'])-1, -1, -1):
312
+ st.success(st.session_state["generated"][i], icon="🤖")
313
+ st.info(st.session_state["past"][i], icon="🧐")
314
+ else:
315
+ st.warning(
316
+ 'Plesase Process RFP Details to access this feature', icon="⚠️")
317
+
318
+ if menu_choice == 'User Stories':
319
+ if st.session_state["is_data_processed"] == True:
320
+ st.title("User Stories")
321
+ st.button("Genrate User Stories", type="primary",
322
+ on_click=genrate_user_stories)
323
+ if st.session_state["is_user_stories_created"] == True:
324
+ st.button("Genrate technical Stories", type="primary",
325
+ on_click=genrate_technical_stories)
326
+ st.button("Export Stories", on_click=export_stories)
327
+ with st.container():
328
+ df = pd.DataFrame(st.session_state["user_stories_json"])
329
+ st.table(df)
330
+ st.markdown(st.session_state["user_stories"])
331
+ else:
332
+ st.warning(
333
+ 'Plesase Process RFP Details to access this feature', icon="⚠️")
334
+
335
+ if menu_choice == 'Summary':
336
+ if st.session_state["is_data_processed"] == True:
337
+ st.title("Summary")
338
+ with st.container():
339
+ st.markdown(st.session_state["rfp_summary"])
340
+ else:
341
+ st.warning(
342
+ 'Plesase Process RFP Details to access this feature', icon="⚠️")
343
+
344
+
345
+ if __name__ == '__main__':
346
+ main()