RAHULJUNEJA33 commited on
Commit
3e6a57e
·
verified ·
1 Parent(s): c4df43e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +183 -140
app.py CHANGED
@@ -2,25 +2,45 @@ import os
2
  import openai
3
  import matplotlib.pyplot as plt
4
  from docx import Document
5
- from docx.shared import Inches
 
6
  from datetime import datetime
7
  import streamlit as st
8
- from openai import OpenAI # New import style
9
 
10
  # Initialize OpenAI client
11
  client = OpenAI(api_key=st.secrets.get("OPENAI_API_KEY"))
12
 
13
- # Check if the API key is loaded correctly
14
- if not client.api_key:
15
- st.error("OpenAI API key is missing in Streamlit secrets.")
16
- else:
17
- st.write("OpenAI API Key loaded successfully.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
  def generate_text(prompt, role="user"):
20
- """Generate text using the OpenAI API (v1.0+ compatible)"""
21
  try:
22
  response = client.chat.completions.create(
23
- model="gpt-4-1106-preview", # Updated model name
24
  messages=[
25
  {"role": "system", "content": "You are an expert banking analyst."},
26
  {"role": role, "content": prompt}
@@ -29,134 +49,157 @@ def generate_text(prompt, role="user"):
29
  return response.choices[0].message.content
30
  except Exception as e:
31
  st.error(f"Error generating text: {e}")
32
- return "(*Failed to generate content. Please review manually.*)"
33
-
34
- # Document creation remains the same
35
- doc = Document()
36
- doc.add_heading('Functional Specification Document (FSD)', level=1)
37
- doc.add_paragraph("**Project Name:** Banking Loan & Fraud Detection System")
38
- doc.add_paragraph("**Version:** 1.0")
39
- doc.add_paragraph("**Prepared By:** Your Name")
40
- doc.add_paragraph(f"**Date:** {datetime.now().strftime('%d/%m/%Y')}")
41
-
42
- # Table of Contents
43
- doc.add_page_break()
44
- doc.add_heading("Table of Contents", level=2)
45
- toc = [
46
- "1. Introduction",
47
- "2. System Overview",
48
- "3. Functional Requirements",
49
- "4. Non-Functional Requirements",
50
- "5. Security & Compliance",
51
- "6. System Architecture Diagram",
52
- "7. Process Flow Diagrams",
53
- "8. UI Mockups",
54
- "9. Assumptions and Constraints",
55
- "10. Dependencies",
56
- "11. Acceptance Criteria",
57
- "12. Glossary",
58
- "13. References"
59
- ]
60
- for item in toc:
61
- doc.add_paragraph(item)
62
-
63
- # Generate Content Using AI
64
- doc.add_page_break()
65
- doc.add_heading("1. Introduction", level=2)
66
- intro_text = generate_text("Write an introduction for a banking loan and fraud detection system FSD.")
67
- doc.add_paragraph(intro_text)
68
-
69
- doc.add_heading("2. System Overview", level=2)
70
- overview_text = generate_text("Write a detailed system overview of a banking fraud detection and loan system.")
71
- doc.add_paragraph(overview_text)
72
-
73
- # Functional Requirements
74
- doc.add_heading("3. Functional Requirements", level=2)
75
- functional_reqs = generate_text("List functional requirements for a banking fraud detection and loan system.")
76
- doc.add_paragraph(functional_reqs)
77
-
78
- # Non-Functional Requirements
79
- doc.add_heading("4. Non-Functional Requirements", level=2)
80
- non_functional_reqs = generate_text("List non-functional requirements for a banking loan and fraud detection system.")
81
- doc.add_paragraph(non_functional_reqs)
82
-
83
- # Security & Compliance
84
- doc.add_heading("5. Security & Compliance", level=2)
85
- security_text = generate_text("What are the security and compliance requirements for a banking loan system?")
86
- doc.add_paragraph(security_text)
87
-
88
- # Generate System Architecture Diagram
89
- doc.add_heading("6. System Architecture Diagram", level=2)
90
- fig, ax = plt.subplots(figsize=(6, 4))
91
- ax.text(0.5, 0.85, "Customer", fontsize=12, ha="center",
92
- bbox=dict(facecolor="lightblue", edgecolor="black"))
93
- ax.text(0.5, 0.65, "Banking System", fontsize=12, ha="center",
94
- bbox=dict(facecolor="lightgreen", edgecolor="black"))
95
- ax.text(0.3, 0.45, "Loan Processing", fontsize=12, ha="center",
96
- bbox=dict(facecolor="lightyellow", edgecolor="black"))
97
- ax.text(0.7, 0.45, "Fraud Detection", fontsize=12, ha="center",
98
- bbox=dict(facecolor="lightpink", edgecolor="black"))
99
- ax.text(0.5, 0.25, "Database", fontsize=12, ha="center",
100
- bbox=dict(facecolor="lightgray", edgecolor="black"))
101
-
102
- ax.set_xlim(0, 1)
103
- ax.set_ylim(0, 1)
104
- ax.set_xticks([])
105
- ax.set_yticks([])
106
- ax.set_frame_on(False)
107
-
108
- # Save diagram
109
- output_folder = "output"
110
- os.makedirs(output_folder, exist_ok=True)
111
-
112
- if os.path.exists(output_folder):
113
- st.write(f"Output folder exists: {output_folder}")
114
- else:
115
- st.error(f"Failed to create output folder: {output_folder}")
116
-
117
- diagram_path = os.path.join(output_folder, "banking_system_architecture.png")
118
- plt.savefig(diagram_path)
119
- plt.close(fig)
120
-
121
- # Insert diagram into document
122
- doc.add_picture(diagram_path, width=Inches(5))
123
-
124
- # Process Flow Diagrams
125
- doc.add_heading("7. Process Flow Diagrams", level=2)
126
- doc.add_paragraph("(*Placeholder for detailed banking process flow diagrams*)")
127
-
128
- # UI Mockups
129
- doc.add_heading("8. UI Mockups", level=2)
130
- doc.add_paragraph("(*Placeholder for UI Mockups for loan applications, fraud alerts, and account dashboards*)")
131
-
132
- # Assumptions and Constraints
133
- doc.add_heading("9. Assumptions and Constraints", level=2)
134
- assumptions_text = generate_text("List assumptions and constraints for a banking loan and fraud detection system.")
135
- doc.add_paragraph(assumptions_text)
136
-
137
- # Dependencies
138
- doc.add_heading("10. Dependencies", level=2)
139
- dependencies_text = generate_text("List the dependencies for a banking loan and fraud detection system project.")
140
- doc.add_paragraph(dependencies_text)
141
-
142
- # Acceptance Criteria
143
- doc.add_heading("11. Acceptance Criteria", level=2)
144
- acceptance_criteria = generate_text("Define acceptance criteria for a banking loan and fraud detection system.")
145
- doc.add_paragraph(acceptance_criteria)
146
-
147
- # Glossary
148
- doc.add_heading("12. Glossary", level=2)
149
- doc.add_paragraph("(*Placeholder for glossary of terms related to banking, loans, and fraud detection*)")
150
-
151
- # References
152
- doc.add_heading("13. References", level=2)
153
- doc.add_paragraph("(*Placeholder for references including documents, articles, and regulatory guidelines*)")
154
-
155
- # Save Document
156
- doc_path = os.path.join(output_folder, "Banking_FSD.docx")
157
- doc.save(doc_path)
158
-
159
- if os.path.exists(doc_path):
160
- st.write(f"FSD generated successfully at: {doc_path}")
161
- else:
162
- st.error("Failed to generate the FSD document.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2
  import openai
3
  import matplotlib.pyplot as plt
4
  from docx import Document
5
+ from docx.shared import Inches, Pt
6
+ from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
7
  from datetime import datetime
8
  import streamlit as st
9
+ from openai import OpenAI
10
 
11
  # Initialize OpenAI client
12
  client = OpenAI(api_key=st.secrets.get("OPENAI_API_KEY"))
13
 
14
+ # Custom CSS for styling
15
+ st.markdown("""
16
+ <style>
17
+ .stTextInput>div>div>input, .stTextArea>div>div>textarea {
18
+ background-color: #f0f2f6;
19
+ border-radius: 5px;
20
+ }
21
+ .stButton>button {
22
+ background-color: #4CAF50;
23
+ color: white;
24
+ padding: 10px 24px;
25
+ border-radius: 5px;
26
+ border: none;
27
+ }
28
+ .stButton>button:hover {
29
+ background-color: #45a049;
30
+ }
31
+ </style>
32
+ """, unsafe_allow_html=True)
33
+
34
+ def init_session_state():
35
+ if 'current_step' not in st.session_state:
36
+ st.session_state.current_step = 1
37
+ if 'user_inputs' not in st.session_state:
38
+ st.session_state.user_inputs = {}
39
 
40
  def generate_text(prompt, role="user"):
 
41
  try:
42
  response = client.chat.completions.create(
43
+ model="gpt-4-1106-preview",
44
  messages=[
45
  {"role": "system", "content": "You are an expert banking analyst."},
46
  {"role": role, "content": prompt}
 
49
  return response.choices[0].message.content
50
  except Exception as e:
51
  st.error(f"Error generating text: {e}")
52
+ return "(*Content generation failed. Please fill manually.*)"
53
+
54
+ def create_fsd_document(inputs):
55
+ doc = Document()
56
+
57
+ # Set default font
58
+ style = doc.styles['Normal']
59
+ font = style.font
60
+ font.name = 'Calibri'
61
+ font.size = Pt(11)
62
+
63
+ # Title Page
64
+ doc.add_heading('Functional Specification Document (FSD)', 0)
65
+ doc.add_paragraph("Project Name: " + inputs.get('project_name', 'Banking System'))
66
+ doc.add_paragraph(f"Version: {inputs.get('version', '1.0')}")
67
+ doc.add_paragraph(f"Prepared By: {inputs.get('author', 'Your Name')}")
68
+ doc.add_paragraph(f"Date: {datetime.now().strftime('%d/%m/%Y')}")
69
+ doc.add_page_break()
70
+
71
+ # Table of Contents
72
+ doc.add_heading("Table of Contents", 1)
73
+ toc = [
74
+ "1. Introduction",
75
+ "2. System Overview",
76
+ "3. Functional Requirements",
77
+ "4. Non-Functional Requirements",
78
+ "5. Security & Compliance",
79
+ "6. System Architecture",
80
+ "7. Process Flows",
81
+ "8. Data Requirements",
82
+ "9. User Interface",
83
+ "10. Reporting",
84
+ "11. Error Handling",
85
+ "12. Assumptions",
86
+ "13. Dependencies",
87
+ "14. Glossary"
88
+ ]
89
+ for item in toc:
90
+ doc.add_paragraph(item, style='ListBullet')
91
+ doc.add_page_break()
92
+
93
+ # Detailed Sections
94
+ sections = {
95
+ "1. Introduction": f"Write a comprehensive introduction for {inputs['project_name']} covering: {inputs['brief_description']}",
96
+ "2. System Overview": f"Create detailed system overview for {inputs['project_name']} including: {inputs['system_components']}",
97
+ "3. Functional Requirements": f"Expand these functional requirements into detailed specifications: {inputs['functional_reqs']}",
98
+ "4. Non-Functional Requirements": f"Create non-functional requirements for: {inputs['non_functional_reqs']}",
99
+ "5. Security & Compliance": f"Detail security measures and compliance requirements for: {inputs['security_needs']}",
100
+ }
101
+
102
+ for header, prompt in sections.items():
103
+ doc.add_heading(header, level=1)
104
+ content = generate_text(prompt)
105
+ for paragraph in content.split('\n'):
106
+ if paragraph.strip():
107
+ p = doc.add_paragraph(paragraph)
108
+ p.paragraph_format.space_after = Pt(6)
109
+
110
+ # Add detailed subsections
111
+ if header == "3. Functional Requirements":
112
+ doc.add_heading("3.1 Detailed Use Cases", level=2)
113
+ use_cases = generate_text(f"Create detailed use cases for: {inputs['functional_reqs']}")
114
+ doc.add_paragraph(use_cases)
115
+
116
+ doc.add_page_break()
117
+
118
+ # Add diagrams
119
+ doc.add_heading("6. System Architecture", 1)
120
+ fig = create_architecture_diagram()
121
+ diagram_path = "system_architecture.png"
122
+ fig.savefig(diagram_path)
123
+ doc.add_picture(diagram_path, width=Inches(6))
124
+
125
+ return doc
126
+
127
+ def create_architecture_diagram():
128
+ fig, ax = plt.subplots(figsize=(10, 6))
129
+ components = [
130
+ ("User Interface", 0.5, 0.9),
131
+ ("Application Layer", 0.3, 0.7),
132
+ ("Business Logic", 0.7, 0.7),
133
+ ("Database", 0.5, 0.5),
134
+ ("External APIs", 0.5, 0.3)
135
+ ]
136
+
137
+ for text, x, y in components:
138
+ ax.text(x, y, text,
139
+ ha='center', va='center',
140
+ bbox=dict(facecolor='lightblue', edgecolor='black', boxstyle='round,pad=0.5'),
141
+ fontsize=10)
142
+
143
+ ax.set_xlim(0, 1)
144
+ ax.set_ylim(0, 1)
145
+ ax.axis('off')
146
+ return fig
147
+
148
+ def main():
149
+ init_session_state()
150
+ st.title("FSD Document Generator")
151
+ st.subheader("Create Custom Functional Specification Documents")
152
+
153
+ if st.session_state.current_step == 1:
154
+ with st.form("basic_info"):
155
+ st.header("Step 1: Basic Information")
156
+ st.session_state.user_inputs['project_name'] = st.text_input("Project Name")
157
+ st.session_state.user_inputs['brief_description'] = st.text_area("Brief Description", height=150)
158
+ if st.form_submit_button("Next "):
159
+ st.session_state.current_step = 2
160
+ st.rerun()
161
+
162
+ elif st.session_state.current_step == 2:
163
+ with st.form("detailed_info"):
164
+ st.header("Step 2: Detailed Requirements")
165
+ st.session_state.user_inputs['functional_reqs'] = st.text_area(
166
+ "Functional Requirements (comma-separated)",
167
+ height=100,
168
+ value="User authentication, Transaction monitoring, Report generation"
169
+ )
170
+ st.session_state.user_inputs['non_functional_reqs'] = st.text_input(
171
+ "Non-Functional Requirements",
172
+ value="High availability, GDPR compliance"
173
+ )
174
+ st.session_state.user_inputs['security_needs'] = st.text_input(
175
+ "Security Requirements",
176
+ value="Data encryption, Role-based access control"
177
+ )
178
+ if st.form_submit_button("Generate FSD"):
179
+ st.session_state.current_step = 3
180
+ st.rerun()
181
+
182
+ elif st.session_state.current_step == 3:
183
+ st.header("Step 3: Generated Document")
184
+ with st.spinner("Generating 10+ page FSD document..."):
185
+ doc = create_fsd_document(st.session_state.user_inputs)
186
+ output_folder = "generated_docs"
187
+ os.makedirs(output_folder, exist_ok=True)
188
+ doc_path = os.path.join(output_folder, "FSD_Document.docx")
189
+ doc.save(doc_path)
190
+
191
+ with open(doc_path, "rb") as file:
192
+ st.download_button(
193
+ label="Download FSD Document",
194
+ data=file,
195
+ file_name="FSD_Document.docx",
196
+ mime="application/vnd.openxmlformats-officedocument.wordprocessingml.document"
197
+ )
198
+
199
+ if st.button("Start New Document"):
200
+ st.session_state.current_step = 1
201
+ st.session_state.user_inputs = {}
202
+ st.rerun()
203
+
204
+ if __name__ == "__main__":
205
+ main()