bluenevus commited on
Commit
0a5f6d7
·
1 Parent(s): 034b23e

Update app.py via AI Editor

Browse files
Files changed (1) hide show
  1. app.py +439 -395
app.py CHANGED
@@ -1,428 +1,472 @@
 
 
 
 
 
 
1
  import dash
2
- from dash import dcc, html, Input, Output, State, callback_context, no_update
3
  import dash_bootstrap_components as dbc
 
 
 
 
 
4
  import logging
5
  import threading
6
- import os
7
- import base64
8
- import io
9
- import uuid
10
- import time
11
- from flask import Flask
12
-
13
- import requests
14
-
15
- ALLOWED_EXTENSIONS = ('pdf', 'doc', 'docx', 'txt')
16
-
17
- logging.basicConfig(
18
- format="%(asctime)s %(levelname)s:%(message)s",
19
- level=logging.INFO
20
- )
21
- logger = logging.getLogger(__name__)
22
-
23
- uploaded_documents = {}
24
- generated_content = {}
25
-
26
- ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages"
27
- ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "YOUR_ANTHROPIC_API_KEY")
28
 
29
- server = Flask(__name__)
30
-
31
- os.environ["CUDA_VISIBLE_DEVICES"] = "0"
32
-
33
- external_stylesheets = [dbc.themes.BOOTSTRAP]
34
-
35
- app = dash.Dash(
36
- __name__,
37
- server=server,
38
- external_stylesheets=external_stylesheets,
39
- suppress_callback_exceptions=True,
40
- title="Proposal Writing Assistant"
41
- )
42
-
43
- def allowed_file(filename):
44
- return '.' in filename and filename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS
45
-
46
- def save_uploaded_file(file_content, filename):
47
- doc_id = str(uuid.uuid4())
48
- uploaded_documents[doc_id] = {
49
- "filename": filename,
50
- "content": file_content
51
- }
52
- logger.info(f"Uploaded document saved: {filename} with id {doc_id}")
53
- return doc_id
54
-
55
- def anthropic_api_call(prompt, files=None, task_type=None, extra_instructions=""):
56
- logger.info(f"Calling Anthropic API for task: {task_type}")
57
- headers = {
58
- "x-api-key": ANTHROPIC_API_KEY,
59
- "content-type": "application/json"
60
- }
61
- data = {
62
- "model": "claude-3-opus-20240229",
63
- "messages": [
64
- {"role": "user", "content": prompt + "\n" + extra_instructions}
65
- ],
66
- "max_tokens": 4096,
67
- "temperature": 0.2
68
- }
69
- try:
70
- # response = requests.post(ANTHROPIC_API_URL, headers=headers, json=data, timeout=120)
71
- # result = response.json().get('content', ['[Anthropic response placeholder]'])[0]
72
- time.sleep(2)
73
- result = f"[Simulated response for {task_type}]"
74
- logger.info(f"Anthropic API success for task: {task_type}")
75
- return result
76
- except Exception as e:
77
- logger.error(f"Anthropic API error: {str(e)}")
78
- return f"Error: {str(e)}"
79
-
80
- def parse_contents(contents, filename):
81
- content_type, content_string = contents.split(',')
82
- decoded = base64.b64decode(content_string)
83
- try:
84
- if filename.lower().endswith('.txt'):
85
- preview = decoded.decode('utf-8')[:2048]
86
- else:
87
- preview = f"Preview not available for {filename}"
88
- return preview
89
- except Exception as e:
90
- logger.error(f"Could not decode file {filename}: {e}")
91
- return f"Error decoding {filename}"
92
-
93
- def navbar():
94
- return dbc.Card(
95
- [
96
- dbc.Nav(
97
- [
98
- dbc.Button("Shred RFP/PWS/SOW/RFI", id="btn-shred", className="mb-2 btn-primary", style={"width": "100%"}),
99
- dbc.Button("Generate Proposal Response", id="btn-generate", className="mb-2 btn-secondary", style={"width": "100%"}),
100
- dbc.Button("Check Compliance", id="btn-compliance", className="mb-2 btn-tertiary", style={"width": "100%"}),
101
- dbc.Button("Recover Document", id="btn-recover", className="mb-2 btn-primary", style={"width": "100%"}),
102
- dbc.Button("Virtual Board", id="btn-virtual-board", className="mb-2 btn-secondary", style={"width": "100%"}),
103
- dbc.Button("Estimate LOE", id="btn-loe", className="mb-2 btn-tertiary", style={"width": "100%"}),
104
- ],
105
- vertical=True,
106
- pills=False
107
  ),
 
 
 
108
  html.Hr(),
109
- html.Div(
110
- [
111
- html.H6("Uploaded Documents"),
112
- html.Ul(
113
- id="uploaded-doc-list",
114
- style={"listStyleType": "none", "paddingLeft": "0"}
115
- ),
116
  ]
 
 
 
 
 
 
 
 
 
 
 
117
  ),
118
- ],
119
- body=True
120
- )
121
-
122
- def chat_window():
123
- return dbc.Card(
124
- [
125
- html.Div(
126
- [
127
- html.Div(id="chat-history", style={"height": "160px", "overflowY": "auto", "padding": "0.5rem"}),
128
- dbc.InputGroup(
129
- [
130
- dbc.Textarea(id="chat-input", placeholder="Send additional instructions...", style={"resize":"vertical", "wordWrap":"break-word", "width": "100%", "height": "60px"}),
131
- dbc.Button("Send", id="btn-send-chat", className="btn-secondary", n_clicks=0),
132
- ],
133
- className="mt-2"
134
- ),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
135
  ]
136
- ),
137
- ],
138
- body=True,
139
- style={"marginBottom": "10px"}
140
- )
141
-
142
- def top_action_buttons():
143
- return html.Div(
144
- [
145
- dbc.Button("Shred", id="action-shred", className="me-2 btn-primary", n_clicks=0, style={"minWidth": "120px"}),
146
- dbc.Button("Generate Response", id="action-generate", className="me-2 btn-secondary", n_clicks=0, style={"minWidth": "180px"}),
147
- dbc.Button("Check Compliance", id="action-compliance", className="me-2 btn-tertiary", n_clicks=0, style={"minWidth": "160px"}),
148
- dbc.Button("Recover", id="action-recover", className="me-2 btn-primary", n_clicks=0, style={"minWidth": "120px"}),
149
- dbc.Button("Virtual Board", id="action-virtual-board", className="me-2 btn-secondary", n_clicks=0, style={"minWidth": "160px"}),
150
- dbc.Button("Estimate LOE", id="action-loe", className="btn-tertiary", n_clicks=0, style={"minWidth": "140px"}),
151
- ],
152
- className="mb-3",
153
- style={"display": "flex", "flexWrap": "wrap"}
154
- )
155
 
156
- def upload_area():
157
- return html.Div(
158
- [
 
 
 
 
159
  dcc.Upload(
160
- id="upload-document",
161
- children=html.Div(["Drag & drop or click to select a file."]),
162
- multiple=False,
 
 
163
  style={
164
- "width": "100%",
165
- "height": "70px",
166
- "lineHeight": "70px",
167
- "borderWidth": "1px",
168
- "borderStyle": "dashed",
169
- "borderRadius": "4px",
170
- "textAlign": "center",
171
- "marginBottom": "8px"
172
- }
 
173
  ),
174
- html.Div(id="upload-feedback")
175
- ]
176
- )
177
-
178
- def preview_area():
179
- return dbc.Card(
180
- [
181
- html.H6("Document Preview / Output"),
182
- html.Pre(id="preview-content", style={"whiteSpace": "pre-wrap", "wordWrap": "break-word", "maxHeight": "340px", "overflowY": "auto"})
183
- ],
184
- body=True
185
- )
186
-
187
- def main_layout():
188
- return dbc.Container(
189
- [
190
- dbc.Row(
191
- [
192
- dbc.Col(
193
- html.H2("Proposal Writing Assistant", style={"margin": "12px 0"}),
194
- width=12
195
- ),
196
- ],
197
- align="center",
198
- style={"marginBottom": "8px"}
199
- ),
200
- dbc.Row(
201
- [
202
- dbc.Col(
203
- navbar(),
204
- width=3,
205
- style={"minWidth": "220px", "maxWidth": "400px"}
206
- ),
207
- dbc.Col(
208
- dbc.Card(
209
- [
210
- chat_window(),
211
- top_action_buttons(),
212
- upload_area(),
213
- preview_area(),
214
- dcc.Loading(
215
- id="loading",
216
- type="default",
217
- children=html.Div(id="loading-output"),
218
- style={"position": "absolute", "top": "6px", "left": "50%"}
219
- ),
220
- ],
221
- body=True
222
- ),
223
- width=9
224
- ),
225
- ],
226
- style={"minHeight": "90vh"}
227
- ),
228
- ],
229
- fluid=True
230
- )
231
 
232
- app.layout = main_layout
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
233
 
234
  @app.callback(
235
- Output("uploaded-doc-list", "children"),
236
- Output("preview-content", "children"),
237
- Output("upload-feedback", "children"),
238
- Output("loading-output", "children"),
239
- Output("chat-history", "children"),
240
- [
241
- Input("upload-document", "contents"),
242
- Input("action-shred", "n_clicks"),
243
- Input("action-generate", "n_clicks"),
244
- Input("action-compliance", "n_clicks"),
245
- Input("action-recover", "n_clicks"),
246
- Input("action-virtual-board", "n_clicks"),
247
- Input("action-loe", "n_clicks"),
248
- Input("btn-send-chat", "n_clicks"),
249
- Input({"type": "delete-doc-btn", "index": dash.ALL}, "n_clicks"),
250
- ],
251
- [
252
- State("upload-document", "filename"),
253
- State("chat-input", "value"),
254
- State("chat-history", "children"),
255
- State("preview-content", "children"),
256
- State("uploaded-doc-list", "children"),
257
- ],
258
  prevent_initial_call=True
259
  )
260
- def main_callback(
261
- upload_contents, shred, generate, compliance, recover, virtual_board, loe, send_chat, delete_doc_clicks,
262
- upload_filename, chat_input, chat_history, preview_content, uploaded_doc_list
263
- ):
264
- triggered_id = callback_context.triggered[0]["prop_id"].split(".")[0] if callback_context.triggered else None
265
- logger.info(f"Triggered callback: {triggered_id}")
266
-
267
- feedback = no_update
268
- loading_message = ""
269
- new_preview_content = no_update
270
- new_chat_history = chat_history if chat_history else []
271
- doc_list_items = []
272
 
273
- if triggered_id == "upload-document" and upload_contents and upload_filename:
274
- if not allowed_file(upload_filename):
275
- feedback = dbc.Alert("Unsupported file type. Please upload PDF, Word, or TXT.", color="danger", dismissable=True)
 
 
 
 
 
 
 
 
 
 
276
  else:
277
- doc_id = save_uploaded_file(upload_contents, upload_filename)
278
- preview = parse_contents(upload_contents, upload_filename)
279
- new_preview_content = f"{upload_filename}:\n\n{preview}"
280
- feedback = dbc.Alert(f"Uploaded {upload_filename}", color="success", dismissable=True)
281
- logger.info(f"File uploaded: {upload_filename}")
282
-
283
- for doc_id, doc in uploaded_documents.items():
284
- doc_list_items.append(
285
- html.Li(
286
- [
287
- html.Span(doc['filename'], style={"marginRight": "8px"}),
288
- dbc.Button("Delete", id={"type": "delete-doc-btn", "index": doc_id}, color="danger", size="sm", n_clicks=0)
289
- ],
290
- style={"display": "flex", "justifyContent": "space-between", "alignItems": "center", "marginBottom": "5px"}
291
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
292
  )
 
 
 
 
 
 
293
 
294
- if isinstance(delete_doc_clicks, list) and any(delete_doc_clicks):
295
- idx = delete_doc_clicks.index(max(delete_doc_clicks))
296
- doc_ids = list(uploaded_documents.keys())
297
- if idx < len(doc_ids):
298
- deleted_doc = uploaded_documents.pop(doc_ids[idx])
299
- feedback = dbc.Alert(f"Deleted {deleted_doc['filename']}", color="info", dismissable=True)
300
- logger.info(f"Document deleted: {deleted_doc['filename']}")
301
- doc_list_items = [
302
- html.Li(
303
- [
304
- html.Span(doc['filename'], style={"marginRight": "8px"}),
305
- dbc.Button("Delete", id={"type": "delete-doc-btn", "index": doc_id}, color="danger", size="sm", n_clicks=0)
306
- ],
307
- style={"display": "flex", "justifyContent": "space-between", "alignItems": "center", "marginBottom": "5px"}
308
- )
309
- for doc_id, doc in uploaded_documents.items()
310
- ]
311
- new_preview_content = "" if not uploaded_documents else no_update
312
 
313
- if len(uploaded_documents) == 0 and triggered_id not in ["upload-document", "btn-send-chat"]:
314
- feedback = dbc.Alert("Please upload a document before performing actions.", color="warning", dismissable=True)
315
- logger.warning("Attempted action without documents.")
316
- return doc_list_items, new_preview_content, feedback, loading_message, new_chat_history
 
 
 
 
 
 
 
 
 
317
 
318
- if triggered_id == "btn-send-chat" and chat_input and chat_input.strip():
319
- if not isinstance(new_chat_history, list):
320
- new_chat_history = []
321
- new_chat_history.append(html.Div([
322
- html.Strong("You: "), html.Span(chat_input)
323
- ], style={"marginBottom": "0.25rem"}))
324
- feedback = dbc.Alert("Chat message sent. Instructions will be used in next action.", color="info", dismissable=True)
325
- logger.info(f"Chat message sent: {chat_input}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
- last_chat = ""
328
- if isinstance(new_chat_history, list) and new_chat_history:
329
- for item in reversed(new_chat_history):
330
- if isinstance(item, html.Div):
331
- children = item.children
332
- if len(children) > 1 and isinstance(children[1], html.Span):
333
- last_chat = children[1].children
334
- break
335
- elif isinstance(chat_input, str):
336
- last_chat = chat_input
 
 
 
337
 
338
- if triggered_id in ["action-shred", "action-generate", "action-compliance", "action-recover", "action-virtual-board", "action-loe"]:
339
- loading_message = dbc.Alert("Processing request, please wait...", color="primary", dismissable=False, style={"textAlign": "center"})
340
- doc_id, doc = next(iter(uploaded_documents.items()))
341
- file_name = doc['filename']
342
- file_content = doc['content']
343
- action_type = triggered_id.replace("action-", "").replace("-", " ").title()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
344
 
345
- # DECODE the document content for use in the prompt
 
 
 
 
 
 
 
 
 
 
346
  try:
347
- content_type, content_string = file_content.split(',')
348
- decoded = base64.b64decode(content_string)
349
- if file_name.lower().endswith('.txt'):
350
- document_text = decoded.decode('utf-8', errors='replace')
351
- else:
352
- document_text = f"[Start of document {file_name} as base64]\n{decoded[:350].hex()}...[truncated]\n[End of document]"
353
  except Exception as e:
354
- logger.error(f"Could not decode document {file_name} for Anthropic: {e}")
355
- document_text = f"[Could not decode {file_name}]"
356
-
357
- logger.info(f"Sending document content of length {len(document_text)} to Anthropic for {action_type}")
358
-
359
- result_holder = {}
360
-
361
- def threaded_api_call():
362
- if triggered_id == "action-shred":
363
- prompt = (
364
- "Shred this document into requirements, organized by section. "
365
- "Identify requirements by action words (shall, will, perform, etc). "
366
- "Output as spreadsheet: PWS Section, Requirement.\n\n"
367
- f"Document Content:\n{document_text}\n"
368
- )
369
- task_type = "Shred"
370
- elif triggered_id == "action-generate":
371
- prompt = (
372
- "Generate a detailed proposal response, organized by section/subsection. "
373
- "Focus on approach, steps, workflow, people, processes, technology. "
374
- "Include research validation and citations. Address Red Review findings.\n\n"
375
- f"Document Content:\n{document_text}\n"
376
- )
377
- task_type = "Generate Proposal Response"
378
- elif triggered_id == "action-compliance":
379
- prompt = (
380
- "Check compliance of the proposal response against the shredded requirements. "
381
- "Produce a spreadsheet: PWS number, requirement, finding, recommendation.\n\n"
382
- f"Proposal Response Document Content:\n{document_text}\n"
383
- )
384
- task_type = "Check Compliance"
385
- elif triggered_id == "action-recover":
386
- prompt = (
387
- "Using the compliance spreadsheet, improve the document sections. "
388
- "Address recommendations without materially changing content. "
389
- "Organize improvements by PWS section headers/subheaders.\n\n"
390
- f"Document Content:\n{document_text}\n"
391
- )
392
- task_type = "Recover Document"
393
- elif triggered_id == "action-virtual-board":
394
- prompt = (
395
- "Evaluate the proposal based on requirements and evaluation criteria. "
396
- "Generate a section-by-section evaluation spreadsheet using ratings: "
397
- "unsatisfactory, satisfactory, good, very good, excellent. Include explanations. "
398
- "Base evaluation on sections L and M.\n\n"
399
- f"Document Content:\n{document_text}\n"
400
- )
401
- task_type = "Virtual Board"
402
- elif triggered_id == "action-loe":
403
- prompt = (
404
- "Estimate Level of Effort for the proposal. Output spreadsheet: "
405
- "PWS task area, brief description, labor categories, estimated hours per category.\n\n"
406
- f"Document Content:\n{document_text}\n"
407
- )
408
- task_type = "Estimate LOE"
409
- else:
410
- prompt = ""
411
- task_type = "Unknown"
412
- logger.info(f"Prompt to Anthropic for {action_type}: {prompt[:400]}...[truncated]")
413
- result_holder["result"] = anthropic_api_call(prompt, files=[file_content], task_type=task_type, extra_instructions=last_chat or "")
414
-
415
- thread = threading.Thread(target=threaded_api_call)
416
- thread.start()
417
- thread.join()
418
-
419
- result = result_holder.get("result", "[No result]")
420
- generated_content[triggered_id] = result
421
- new_preview_content = f"{action_type} Output for {file_name}:\n\n{result}"
422
- feedback = dbc.Alert(f"{action_type} completed.", color="success", dismissable=True)
423
- logger.info(f"{action_type} completed for {file_name}")
424
-
425
- return doc_list_items, new_preview_content, feedback, loading_message, new_chat_history
426
 
427
  if __name__ == '__main__':
428
  print("Starting the Dash application...")
 
1
+ import base64
2
+ import io
3
+ import os
4
+ import pandas as pd
5
+ from docx import Document
6
+ from io import BytesIO, StringIO
7
  import dash
 
8
  import dash_bootstrap_components as dbc
9
+ from dash import html, dcc, Input, Output, State, callback_context, MATCH, ALL
10
+ from docx.shared import Pt
11
+ from docx.enum.style import WD_STYLE_TYPE
12
+ from PyPDF2 import PdfReader
13
+ import openai
14
  import logging
15
  import threading
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
 
17
+ logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
18
+
19
+ app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP], suppress_callback_exceptions=True)
20
+
21
+ openai.api_key = os.environ.get("OPENAI_API_KEY", "")
22
+
23
+ uploaded_files = {}
24
+ current_document = None
25
+ document_type = None
26
+ shredded_document = None
27
+ pink_review_document = None
28
+ uploaded_doc_contents = {}
29
+
30
+ document_types = {
31
+ "Shred": "Generate a requirements spreadsheet of the Project Work Statement (PWS) identified by action words like shall, will, perform etc. by pws section, requirement. Do not write as if you're responding to the proposal. Its a spreadsheet to distill the requirements, not microhealth's approach",
32
+ "Pink": "Create a Pink Team document based on the PWS outline. Your goal is to be compliant and compelling.",
33
+ "Pink Review": "Evaluate compliance of the Pink Team document against the requirements and output a spreadsheet of non compliant findings by pws number, the goal of that pws section, what made it non compliant and your recommendations for recovery",
34
+ "Red": "Produce a Red Team document based on the Pink Review by pws sections. Your goal is to be compliant and compelling by recovering all the findings in Pink Review",
35
+ "Red Review": "Evaluate compliance of the Red Team document against the requirements and output a spreadsheet of non compliant findings by pws number, the goal of that pws section, what made it non compliant and your recommendations for recovery",
36
+ "Gold": "Create a Pink Team document based on the PWS response by pws sections. Your goal is to be compliant and compelling by recovering all the findings in Red Review",
37
+ "Gold Review": "Perform a final compliance review against the requirements and output a spreadsheet of non compliant findings by pws number, the goal of that pws section, what made it non compliant and your recommendations for recovery",
38
+ "Virtual Board": "Based on the requirements and in particular the evaulation criteria, you will evaluate the proposal as if you were a contracting office and provide section by section evaluation as unsatisfactory, satisfactory, good, very good, excellent and why in a spreadsheet",
39
+ "LOE": "Generate a Level of Effort (LOE) breakdown as a spreadsheet"
40
+ }
41
+
42
+ def get_right_col_content(selected_type):
43
+ if selected_type == "Shred":
44
+ return [
45
+ html.Div([
46
+ html.Div(className="blinking-dot", style={'margin':'0 auto','width':'16px','height':'16px'}),
47
+ ], style={'textAlign':'center', 'marginBottom':'10px'}),
48
+ dcc.Loading(
49
+ id="loading-indicator",
50
+ type="dot",
51
+ children=[html.Div(id="loading-output")]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  ),
53
+ html.Div(id='document-preview', className="border p-3 mb-3"),
54
+ dbc.Button("Download Document", id="btn-download", color="success", className="mt-3"),
55
+ dcc.Download(id="download-document"),
56
  html.Hr(),
57
+ dcc.Loading(
58
+ id="chat-loading",
59
+ type="dot",
60
+ children=[
61
+ dbc.Input(id="chat-input", type="text", placeholder="Chat with AI to update document...", className="mb-2", style={'whiteSpace':'pre-wrap'}),
62
+ dbc.Button("Send", id="btn-send-chat", color="primary", className="mb-3"),
63
+ html.Div(id="chat-output")
64
  ]
65
+ )
66
+ ]
67
+ else:
68
+ return [
69
+ html.Div([
70
+ html.Div(className="blinking-dot", style={'margin':'0 auto','width':'16px','height':'16px'}),
71
+ ], style={'textAlign':'center', 'marginBottom':'10px'}),
72
+ dcc.Loading(
73
+ id="loading-indicator",
74
+ type="dot",
75
+ children=[html.Div(id="loading-output")]
76
  ),
77
+ html.Div(id='document-preview', className="border p-3 mb-3"),
78
+ dbc.Button("Download Document", id="btn-download", color="success", className="mt-3"),
79
+ dcc.Download(id="download-document"),
80
+ html.Hr(),
81
+ html.Div([
82
+ html.Label(f"Upload {selected_type} Document"),
83
+ dcc.Upload(
84
+ id={'type': 'upload-doc-type', 'index': selected_type},
85
+ children=html.Div(['Drag and Drop or ', html.A('Select File')]),
86
+ style={
87
+ 'width': '100%',
88
+ 'height': '60px',
89
+ 'lineHeight': '60px',
90
+ 'borderWidth': '1px',
91
+ 'borderStyle': 'dashed',
92
+ 'borderRadius': '5px',
93
+ 'textAlign': 'center',
94
+ 'margin': '10px 0'
95
+ },
96
+ multiple=False
97
+ ),
98
+ html.Div(id={'type': 'uploaded-doc-name', 'index': selected_type}),
99
+ dbc.RadioItems(
100
+ id={'type': 'radio-doc-source', 'index': selected_type},
101
+ options=[
102
+ {'label': 'Loaded Document', 'value': 'loaded'},
103
+ {'label': 'Uploaded Document', 'value': 'uploaded'}
104
+ ],
105
+ value='loaded',
106
+ inline=True,
107
+ className="mb-2"
108
+ ),
109
+ dbc.Button("Generate Document", id={'type': 'btn-generate-doc', 'index': selected_type}, color="primary", className="mb-3"),
110
+ ], id={'type': 'doc-type-controls', 'index': selected_type}),
111
+ dcc.Loading(
112
+ id="chat-loading",
113
+ type="dot",
114
+ children=[
115
+ dbc.Input(id="chat-input", type="text", placeholder="Chat with AI to update document...", className="mb-2", style={'whiteSpace':'pre-wrap'}),
116
+ dbc.Button("Send", id="btn-send-chat", color="primary", className="mb-3"),
117
+ html.Div(id="chat-output")
118
  ]
119
+ )
120
+ ]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
121
 
122
+ app.layout = dbc.Container([
123
+ dbc.Row([
124
+ dbc.Col([
125
+ html.H4("Proposal Documents", className="mt-3 mb-4"),
126
+ html.Div([
127
+ html.Div(className="blinking-dot", style={'margin':'0 auto','width':'16px','height':'16px'}),
128
+ ], style={'textAlign':'center', 'marginBottom':'10px'}),
129
  dcc.Upload(
130
+ id='upload-document',
131
+ children=html.Div([
132
+ 'Drag and Drop or ',
133
+ html.A('Select Files')
134
+ ]),
135
  style={
136
+ 'width': '100%',
137
+ 'height': '60px',
138
+ 'lineHeight': '60px',
139
+ 'borderWidth': '1px',
140
+ 'borderStyle': 'dashed',
141
+ 'borderRadius': '5px',
142
+ 'textAlign': 'center',
143
+ 'margin': '10px 0'
144
+ },
145
+ multiple=True
146
  ),
147
+ html.Div(id='file-list'),
148
+ html.Hr(),
149
+ html.Div([
150
+ dbc.Button(
151
+ doc_type,
152
+ id={'type': 'btn-doc-type', 'index': doc_type},
153
+ color="link",
154
+ className="mb-2 w-100 text-left custom-button",
155
+ style={'overflow': 'hidden', 'text-overflow': 'ellipsis', 'white-space': 'nowrap'}
156
+ ) for doc_type in document_types.keys()
157
+ ])
158
+ ], width=3),
159
+ dbc.Col([
160
+ html.Div(id='right-col-content')
161
+ ], width=9)
162
+ ])
163
+ ], fluid=True)
164
+
165
+ def process_document(contents, filename):
166
+ content_type, content_string = contents.split(',')
167
+ decoded = base64.b64decode(content_string)
168
+ try:
169
+ if filename.lower().endswith('.docx'):
170
+ doc = Document(BytesIO(decoded))
171
+ text = "\n".join([para.text for para in doc.paragraphs])
172
+ return text
173
+ elif filename.lower().endswith('.pdf'):
174
+ pdf = PdfReader(BytesIO(decoded))
175
+ text = ""
176
+ for page in pdf.pages:
177
+ page_text = page.extract_text()
178
+ if page_text:
179
+ text += page_text
180
+ return text
181
+ else:
182
+ return f"Unsupported file format: {filename}. Please upload a PDF or DOCX file."
183
+ except Exception as e:
184
+ logging.error(f"Error processing document: {str(e)}")
185
+ return f"Error processing document: {str(e)}"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
186
 
187
+ @app.callback(
188
+ Output('file-list', 'children'),
189
+ Input('upload-document', 'contents'),
190
+ State('upload-document', 'filename'),
191
+ State('file-list', 'children')
192
+ )
193
+ def update_output(list_of_contents, list_of_names, existing_files):
194
+ global uploaded_files, shredded_document
195
+ if list_of_contents is not None:
196
+ new_files = []
197
+ for i, (content, name) in enumerate(zip(list_of_contents, list_of_names)):
198
+ file_content = process_document(content, name)
199
+ uploaded_files[name] = file_content
200
+ new_files.append(html.Div([
201
+ html.Button('×', id={'type': 'remove-file', 'index': name}, style={'marginRight': '5px', 'fontSize': '10px'}),
202
+ html.Span(name)
203
+ ]))
204
+ if existing_files is None:
205
+ existing_files = []
206
+ shredded_document = None
207
+ logging.info("Documents uploaded and file list updated.")
208
+ return existing_files + new_files
209
+ return existing_files
210
 
211
  @app.callback(
212
+ Output('file-list', 'children', allow_duplicate=True),
213
+ Input({'type': 'remove-file', 'index': ALL}, 'n_clicks'),
214
+ State('file-list', 'children'),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
  prevent_initial_call=True
216
  )
217
+ def remove_file(n_clicks, existing_files):
218
+ global uploaded_files, shredded_document
219
+ ctx = dash.callback_context
220
+ if not ctx.triggered:
221
+ raise dash.exceptions.PreventUpdate
222
+ removed_file = ctx.triggered[0]['prop_id'].split(',')[0].split(':')[-1].strip('}')
223
+ uploaded_files.pop(removed_file, None)
224
+ shredded_document = None
225
+ logging.info(f"Removed file: {removed_file}")
226
+ return [file for file in existing_files if file['props']['children'][1]['props']['children'] != removed_file]
 
 
227
 
228
+ @app.callback(
229
+ Output('right-col-content', 'children'),
230
+ [Input({'type': 'btn-doc-type', 'index': ALL}, 'n_clicks')],
231
+ [State({'type': 'btn-doc-type', 'index': ALL}, 'id')]
232
+ )
233
+ def update_right_col(n_clicks_list, btn_ids):
234
+ triggered = callback_context.triggered
235
+ if not triggered or all(x is None for x in n_clicks_list):
236
+ selected_type = "Shred"
237
+ else:
238
+ idx = [i for i, x in enumerate(n_clicks_list) if x]
239
+ if idx:
240
+ selected_type = btn_ids[idx[-1]]['index']
241
  else:
242
+ selected_type = "Shred"
243
+ return get_right_col_content(selected_type)
244
+
245
+ def generate_document(document_type, file_contents):
246
+ prompt = f"""Generate a {document_type} based on the following project artifacts:
247
+ {' '.join(file_contents)}
248
+ Instructions:
249
+ 1. Create the {document_type} as a detailed document.
250
+ 2. Use proper formatting and structure.
251
+ 3. Include all necessary sections and details.
252
+ 4. Start the output immediately with the document content.
253
+ 5. IMPORTANT: If the document type is Pink, Red, Gold and not
254
+ Pink Review, Red Review, Gold Review, or spreadsheet, loe or virtual board
255
+ then your goal is to be compliant and compelling based on the
256
+ requrements, write in paragraph in active voice as
257
+ MicroHealth, limit bullets, answer the
258
+ requirement with what MicroHealth will do
259
+ to satisfy the requirement, the technical
260
+ approach with innovation for efficiency,
261
+ productivity, quality and measurable
262
+ outcomes, the industry standard that
263
+ methodology is based on if applicable,
264
+ detail the workflow or steps to accomplish
265
+ the requirement with labor categories that
266
+ will do those tasks in that workflow,
267
+ reference reputable research like gartner,
268
+ forrester, IDC, Deloitte, Accenture etc
269
+ with measures of success and substantiation
270
+ of MicroHealth's approach. Never use soft words
271
+ like maybe, could be, should, possible be definitive in your language and confident.
272
+ 6. you must also take into account section L&M of the document which is the evaluation criteria
273
+ to be sure we address them.
274
+ Now, generate the {document_type}:
275
+ """
276
+
277
+ logging.info(f"Generating document for type: {document_type}")
278
+ try:
279
+ response = openai.ChatCompletion.create(
280
+ model="gpt-4-1106-preview",
281
+ messages=[
282
+ {"role": "system", "content": "You are a helpful, expert government proposal writer."},
283
+ {"role": "user", "content": prompt}
284
+ ],
285
+ max_tokens=4096,
286
+ temperature=0.25,
287
  )
288
+ generated_text = response['choices'][0]['message']['content']
289
+ logging.info("Document generated successfully.")
290
+ return generated_text
291
+ except Exception as e:
292
+ logging.error(f"Error generating document: {str(e)}")
293
+ raise
294
 
295
+ @app.callback(
296
+ Output('document-preview', 'children'),
297
+ Output('loading-output', 'children'),
298
+ Input({'type': 'btn-doc-type', 'index': 'Shred'}, 'n_clicks'),
299
+ prevent_initial_call=True
300
+ )
301
+ def generate_shred_doc(n_clicks):
302
+ global current_document, document_type, shredded_document
303
+ if not uploaded_files:
304
+ return html.Div("Please upload a document before shredding."), ""
305
+ file_contents = list(uploaded_files.values())
306
+ try:
307
+ shredded_document = generate_document("Shred", file_contents)
308
+ current_document = shredded_document
309
+ return dcc.Markdown(shredded_document), "Shred generated"
310
+ except Exception as e:
311
+ logging.error(f"Error generating document: {str(e)}")
312
+ return html.Div(f"Error generating document: {str(e)}"), "Error"
313
 
314
+ @app.callback(
315
+ Output({'type': 'uploaded-doc-name', 'index': MATCH}, 'children'),
316
+ Output({'type': 'upload-doc-type', 'index': MATCH}, 'contents'),
317
+ Input({'type': 'upload-doc-type', 'index': MATCH}, 'contents'),
318
+ State({'type': 'upload-doc-type', 'index': MATCH}, 'filename'),
319
+ State({'type': 'upload-doc-type', 'index': MATCH}, 'id')
320
+ )
321
+ def update_uploaded_doc_name(contents, filename, id_dict):
322
+ if contents is not None:
323
+ uploaded_doc_contents[id_dict['index']] = (contents, filename)
324
+ logging.info(f"{id_dict['index']} file uploaded: {filename}")
325
+ return filename, contents
326
+ return "", None
327
 
328
+ @app.callback(
329
+ Output('document-preview', 'children', allow_duplicate=True),
330
+ Output('loading-output', 'children', allow_duplicate=True),
331
+ Input({'type': 'btn-generate-doc', 'index': ALL}, 'n_clicks'),
332
+ State({'type': 'btn-generate-doc', 'index': ALL}, 'id'),
333
+ State({'type': 'radio-doc-source', 'index': ALL}, 'value'),
334
+ State({'type': 'upload-doc-type', 'index': ALL}, 'contents'),
335
+ State({'type': 'upload-doc-type', 'index': ALL}, 'filename'),
336
+ prevent_initial_call=True
337
+ )
338
+ def generate_other_doc(n_clicks_list, btn_ids, radio_values, upload_contents, upload_filenames):
339
+ global current_document, document_type, shredded_document, pink_review_document
340
+ ctx = callback_context
341
+ if not ctx.triggered:
342
+ raise dash.exceptions.PreventUpdate
343
+ idx = [i for i, x in enumerate(n_clicks_list) if x]
344
+ if not idx:
345
+ raise dash.exceptions.PreventUpdate
346
+ idx = idx[-1]
347
+ doc_type = btn_ids[idx]['index']
348
+ document_type = doc_type
349
+
350
+ if doc_type == "Shred":
351
+ raise dash.exceptions.PreventUpdate
352
+
353
+ if shredded_document is None:
354
+ return html.Div("Please shred a document first."), ""
355
+
356
+ source = radio_values[idx] if radio_values and len(radio_values) > idx else 'loaded'
357
+ doc_content = None
358
+
359
+ if source == 'uploaded':
360
+ if upload_contents and len(upload_contents) > idx and upload_contents[idx] and upload_filenames and len(upload_filenames) > idx and upload_filenames[idx]:
361
+ doc_content = process_document(upload_contents[idx], upload_filenames[idx])
362
+ else:
363
+ return html.Div("Please upload a document to use as source."), ""
364
+ else:
365
+ if doc_type == "Pink":
366
+ doc_content = shredded_document
367
+ elif doc_type == "Pink Review":
368
+ doc_content = pink_review_document if pink_review_document else ""
369
+ elif doc_type == "Red":
370
+ doc_content = pink_review_document if pink_review_document else ""
371
+ elif doc_type == "Red Review":
372
+ doc_content = pink_review_document if pink_review_document else ""
373
+ elif doc_type == "Gold":
374
+ doc_content = shredded_document
375
+ elif doc_type == "Gold Review":
376
+ doc_content = shredded_document
377
+ elif doc_type == "Virtual Board":
378
+ doc_content = shredded_document
379
+ elif doc_type == "LOE":
380
+ doc_content = shredded_document
381
+ else:
382
+ doc_content = shredded_document
383
 
384
+ try:
385
+ if doc_type == "Pink Review":
386
+ current_document = generate_document(doc_type, [doc_content, shredded_document])
387
+ pink_review_document = current_document
388
+ elif doc_type in ["Red", "Red Review"]:
389
+ current_document = generate_document(doc_type, [doc_content, shredded_document])
390
+ else:
391
+ current_document = generate_document(doc_type, [doc_content])
392
+ logging.info(f"{doc_type} document generated successfully.")
393
+ return dcc.Markdown(current_document), f"{doc_type} generated"
394
+ except Exception as e:
395
+ logging.error(f"Error generating document: {str(e)}")
396
+ return html.Div(f"Error generating document: {str(e)}"), "Error"
397
 
398
+ @app.callback(
399
+ Output('chat-output', 'children'),
400
+ Output('document-preview', 'children', allow_duplicate=True),
401
+ Input('btn-send-chat', 'n_clicks'),
402
+ State('chat-input', 'value'),
403
+ prevent_initial_call=True
404
+ )
405
+ def update_document_via_chat(n_clicks, chat_input):
406
+ global current_document, document_type
407
+ if not chat_input or current_document is None:
408
+ raise dash.exceptions.PreventUpdate
409
+
410
+ prompt = f"""Update the following {document_type} based on this instruction: {chat_input}
411
+ Current document:
412
+ {current_document}
413
+ Instructions:
414
+ 1. Provide the updated document content.
415
+ 2. Maintain proper formatting and structure.
416
+ 3. Incorporate the requested changes seamlessly.
417
+ Now, provide the updated {document_type}:
418
+ """
419
+
420
+ logging.info(f"Updating document via chat for {document_type} instruction: {chat_input}")
421
+ try:
422
+ response = openai.ChatCompletion.create(
423
+ model="gpt-4-1106-preview",
424
+ messages=[
425
+ {"role": "system", "content": "You are a helpful, expert government proposal writer."},
426
+ {"role": "user", "content": prompt}
427
+ ],
428
+ max_tokens=4096,
429
+ temperature=0.2,
430
+ )
431
+ current_document = response['choices'][0]['message']['content']
432
+ logging.info("Document updated via chat successfully.")
433
+ return f"Document updated based on: {chat_input}", dcc.Markdown(current_document)
434
+ except Exception as e:
435
+ logging.error(f"Error updating document via chat: {str(e)}")
436
+ return f"Error updating document: {str(e)}", html.Div(f"Error updating document: {str(e)}")
437
 
438
+ @app.callback(
439
+ Output("download-document", "data"),
440
+ Input("btn-download", "n_clicks"),
441
+ prevent_initial_call=True
442
+ )
443
+ def download_document(n_clicks):
444
+ global current_document, document_type
445
+ if current_document is None:
446
+ raise dash.exceptions.PreventUpdate
447
+
448
+ if document_type == "LOE":
449
  try:
450
+ df = pd.read_csv(StringIO(current_document))
451
+ output = BytesIO()
452
+ with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
453
+ df.to_excel(writer, sheet_name='LOE', index=False)
454
+ logging.info("LOE document downloaded as Excel.")
455
+ return dcc.send_bytes(output.getvalue(), f"{document_type}.xlsx")
456
  except Exception as e:
457
+ logging.error(f"Error downloading LOE document: {str(e)}")
458
+ return dcc.send_string(f"Error downloading LOE: {str(e)}", f"{document_type}_error.txt")
459
+ else:
460
+ try:
461
+ doc = Document()
462
+ doc.add_paragraph(current_document)
463
+ output = BytesIO()
464
+ doc.save(output)
465
+ logging.info("Document downloaded as Word.")
466
+ return dcc.send_bytes(output.getvalue(), f"{document_type}.docx")
467
+ except Exception as e:
468
+ logging.error(f"Error downloading document: {str(e)}")
469
+ return dcc.send_string(f"Error downloading document: {str(e)}", f"{document_type}_error.txt")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
470
 
471
  if __name__ == '__main__':
472
  print("Starting the Dash application...")