Spaces:
Paused
Paused
File size: 22,063 Bytes
e60c00e 525d347 bd5de4f 9f4cd2a 67360ee 9341c86 229097a 0a1b210 9f4cd2a e60c00e 579948a e60c00e 9f4cd2a e60c00e 83acb90 67360ee 9341c86 e34874a cb6077d 67360ee cb6077d 9341c86 9f4cd2a 9341c86 43e6676 9341c86 67360ee 9341c86 9f4cd2a 67360ee 43e6676 67360ee 9341c86 67360ee 9341c86 67360ee 9341c86 67360ee 9f4cd2a 67360ee 9341c86 67360ee cb6077d 67360ee e34874a 67360ee 9f4cd2a 67360ee 9f4cd2a 67360ee e34874a 67360ee 9f4cd2a 67360ee cb6077d 67360ee 9341c86 67360ee 9f4cd2a 67360ee 83acb90 9341c86 67360ee 43e6676 9f4cd2a 43e6676 67360ee 9341c86 67360ee 9341c86 67360ee 9341c86 67360ee 9341c86 e34874a 9341c86 e34874a 67360ee 9341c86 67360ee 9341c86 67360ee 9341c86 43e6676 9341c86 67360ee 9341c86 67360ee 9341c86 67360ee 9f4cd2a 9341c86 e34874a 67360ee 9f4cd2a e34874a 67360ee 9f4cd2a 67360ee 9f4cd2a 43e6676 67360ee 9f4cd2a 67360ee |
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 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 |
import base64
import io
import os
import pandas as pd
from docx import Document
from io import BytesIO, StringIO
import dash
import dash_bootstrap_components as dbc
from dash import html, dcc, Input, Output, State, callback_context, MATCH, ALL
from docx.shared import Pt
from docx.enum.style import WD_STYLE_TYPE
from PyPDF2 import PdfReader
import openai
import logging
import threading
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP], suppress_callback_exceptions=True)
openai.api_key = os.environ.get("OPENAI_API_KEY", "")
uploaded_files = {}
current_document = None
document_type = None
shredded_document = None
pink_review_document = None
uploaded_doc_contents = {}
document_types = {
"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",
"Pink": "Create a Pink Team document based on the PWS outline. Your goal is to be compliant and compelling.",
"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",
"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",
"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",
"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",
"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",
"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",
"LOE": "Generate a Level of Effort (LOE) breakdown as a spreadsheet"
}
def get_right_col_content(selected_type):
if selected_type == "Shred":
return [
html.Div([
html.Div(className="blinking-dot", style={'margin':'0 auto','width':'16px','height':'16px'}),
], style={'textAlign':'center', 'marginBottom':'10px'}),
html.Div(id='status-bar', className="alert alert-info", style={'marginBottom': '20px'}),
dcc.Loading(
id="loading-indicator",
type="dot",
children=[html.Div(id="loading-output")]
),
html.Div(id='document-preview', className="border p-3 mb-3"),
dbc.Button("Download Document", id="btn-download", color="success", className="mt-3"),
dcc.Download(id="download-document"),
html.Hr(),
dcc.Loading(
id="chat-loading",
type="dot",
children=[
dbc.Input(id="chat-input", type="text", placeholder="Chat with AI to update document...", className="mb-2", style={'whiteSpace':'pre-wrap'}),
dbc.Button("Send", id="btn-send-chat", color="primary", className="mb-3"),
html.Div(id="chat-output")
]
)
]
else:
return [
html.Div([
html.Div(className="blinking-dot", style={'margin':'0 auto','width':'16px','height':'16px'}),
], style={'textAlign':'center', 'marginBottom':'10px'}),
html.Div(id='status-bar', className="alert alert-info", style={'marginBottom': '20px'}),
dcc.Loading(
id="loading-indicator",
type="dot",
children=[html.Div(id="loading-output")]
),
html.Div(id='document-preview', className="border p-3 mb-3"),
dbc.Button("Download Document", id="btn-download", color="success", className="mt-3"),
dcc.Download(id="download-document"),
html.Hr(),
html.Div([
html.Label(f"Upload {selected_type} Document"),
dcc.Upload(
id={'type': 'upload-doc-type', 'index': selected_type},
children=html.Div(['Drag and Drop or ', html.A('Select File')]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px 0'
},
multiple=False
),
html.Div(id={'type': 'uploaded-doc-name', 'index': selected_type}),
dbc.RadioItems(
id={'type': 'radio-doc-source', 'index': selected_type},
options=[
{'label': 'Loaded Document', 'value': 'loaded'},
{'label': 'Uploaded Document', 'value': 'uploaded'}
],
value='loaded',
inline=True,
className="mb-2"
),
dbc.Button("Generate Document", id={'type': 'btn-generate-doc', 'index': selected_type}, color="primary", className="mb-3"),
], id={'type': 'doc-type-controls', 'index': selected_type}),
dcc.Loading(
id="chat-loading",
type="dot",
children=[
dbc.Input(id="chat-input", type="text", placeholder="Chat with AI to update document...", className="mb-2", style={'whiteSpace':'pre-wrap'}),
dbc.Button("Send", id="btn-send-chat", color="primary", className="mb-3"),
html.Div(id="chat-output")
]
)
]
app.layout = dbc.Container([
dbc.Row([
dbc.Col([
html.H4("Proposal Documents", className="mt-3 mb-4"),
html.Div([
html.Div(className="blinking-dot", style={'margin':'0 auto','width':'16px','height':'16px'}),
], style={'textAlign':'center', 'marginBottom':'10px'}),
dcc.Upload(
id='upload-document',
children=html.Div([
'Drag and Drop or ',
html.A('Select Files')
]),
style={
'width': '100%',
'height': '60px',
'lineHeight': '60px',
'borderWidth': '1px',
'borderStyle': 'dashed',
'borderRadius': '5px',
'textAlign': 'center',
'margin': '10px 0'
},
multiple=True
),
html.Div(id='file-list'),
html.Hr(),
html.Div([
dbc.Button(
doc_type,
id={'type': 'btn-doc-type', 'index': doc_type},
color="link",
className="mb-2 w-100 text-left custom-button",
style={'overflow': 'hidden', 'text-overflow': 'ellipsis', 'white-space': 'nowrap'}
) for doc_type in document_types.keys()
])
], width=3),
dbc.Col([
html.Div(id='right-col-content')
], width=9)
])
], fluid=True)
def process_document(contents, filename):
content_type, content_string = contents.split(',')
decoded = base64.b64decode(content_string)
try:
if filename.lower().endswith('.docx'):
doc = Document(BytesIO(decoded))
text = "\n".join([para.text for para in doc.paragraphs])
return text
elif filename.lower().endswith('.pdf'):
pdf = PdfReader(BytesIO(decoded))
text = ""
for page in pdf.pages:
page_text = page.extract_text()
if page_text:
text += page_text
return text
else:
return f"Unsupported file format: {filename}. Please upload a PDF or DOCX file."
except Exception as e:
logging.error(f"Error processing document: {str(e)}")
return f"Error processing document: {str(e)}"
@app.callback(
Output('file-list', 'children'),
Output('status-bar', 'children'),
Input('upload-document', 'contents'),
State('upload-document', 'filename'),
State('file-list', 'children')
)
def update_output(list_of_contents, list_of_names, existing_files):
global uploaded_files, shredded_document
if list_of_contents is not None:
new_files = []
for i, (content, name) in enumerate(zip(list_of_contents, list_of_names)):
file_content = process_document(content, name)
uploaded_files[name] = file_content
new_files.append(html.Div([
html.Button('×', id={'type': 'remove-file', 'index': name}, style={'marginRight': '5px', 'fontSize': '10px'}),
html.Span(name)
]))
if existing_files is None:
existing_files = []
shredded_document = None
logging.info("Documents uploaded and file list updated.")
return existing_files + new_files, "Document uploaded. Please click 'Shred' to proceed."
return existing_files, "Please upload a document and click 'Shred' to begin."
@app.callback(
Output('file-list', 'children', allow_duplicate=True),
Output('status-bar', 'children', allow_duplicate=True),
Input({'type': 'remove-file', 'index': ALL}, 'n_clicks'),
State('file-list', 'children'),
prevent_initial_call=True
)
def remove_file(n_clicks, existing_files):
global uploaded_files, shredded_document
ctx = dash.callback_context
if not ctx.triggered:
raise dash.exceptions.PreventUpdate
removed_file = ctx.triggered[0]['prop_id'].split(',')[0].split(':')[-1].strip('}')
uploaded_files.pop(removed_file, None)
shredded_document = None
logging.info(f"Removed file: {removed_file}")
return [file for file in existing_files if file['props']['children'][1]['props']['children'] != removed_file], "Document removed. Please upload a document and click 'Shred' to begin."
@app.callback(
Output('right-col-content', 'children'),
[Input({'type': 'btn-doc-type', 'index': ALL}, 'n_clicks')],
[State({'type': 'btn-doc-type', 'index': ALL}, 'id')]
)
def update_right_col(n_clicks_list, btn_ids):
triggered = callback_context.triggered
if not triggered or all(x is None for x in n_clicks_list):
selected_type = "Shred"
else:
idx = [i for i, x in enumerate(n_clicks_list) if x]
if idx:
selected_type = btn_ids[idx[-1]]['index']
else:
selected_type = "Shred"
return get_right_col_content(selected_type)
def generate_document(document_type, file_contents):
prompt = f"""Generate a {document_type} based on the following project artifacts:
{' '.join(file_contents)}
Instructions:
1. Create the {document_type} as a detailed document.
2. Use proper formatting and structure.
3. Include all necessary sections and details.
4. Start the output immediately with the document content.
5. IMPORTANT: If the document type is Pink, Red, Gold and not review type, loe or board
then your goal is to be compliant and compelling based on the
requrements, write in paragraph in active voice as
MicroHealth, limit bullets, answer the
requirement with what MicroHealth will do
to satisfy the requirement, the technical
approach with innovation for efficiency,
productivity, quality and measurable
outcomes, the industry standard that
methodology is based on if applicable,
detail the workflow or steps to accomplish
the requirement with labor categories that
will do those tasks in that workflow,
reference reputable research like gartner,
forrester, IDC, Deloitte, Accenture etc
with measures of success and substantiation
of MicroHealth's approach. Never use soft words
like maybe, could be, should, possible be definitive in your language and confident.
6. you must also take into account section L&M of the document which is the evaluation criteria
to be sure we address them.
Now, generate the {document_type}:
"""
logging.info(f"Generating document for type: {document_type}")
try:
response = openai.ChatCompletion.create(
model="gpt-4-1106-preview",
messages=[
{"role": "system", "content": "You are a helpful, expert government proposal writer."},
{"role": "user", "content": prompt}
],
max_tokens=4096,
temperature=0.25,
)
generated_text = response['choices'][0]['message']['content']
logging.info("Document generated successfully.")
return generated_text
except Exception as e:
logging.error(f"Error generating document: {str(e)}")
raise
@app.callback(
Output('document-preview', 'children'),
Output('loading-output', 'children'),
Output('status-bar', 'children', allow_duplicate=True),
Input({'type': 'btn-doc-type', 'index': 'Shred'}, 'n_clicks'),
prevent_initial_call=True
)
def generate_shred_doc(n_clicks):
global current_document, document_type, shredded_document
if not uploaded_files:
return html.Div("Please upload a document before shredding."), "", "Please upload a document before shredding."
file_contents = list(uploaded_files.values())
try:
shredded_document = generate_document("Shred", file_contents)
current_document = shredded_document
return dcc.Markdown(shredded_document), "Shred generated", "Document shredded. You can now proceed with other operations."
except Exception as e:
logging.error(f"Error generating document: {str(e)}")
return html.Div(f"Error generating document: {str(e)}"), "Error", "An error occurred while shredding the document."
@app.callback(
Output({'type': 'uploaded-doc-name', 'index': MATCH}, 'children'),
Output({'type': 'upload-doc-type', 'index': MATCH}, 'contents'),
Input({'type': 'upload-doc-type', 'index': MATCH}, 'contents'),
State({'type': 'upload-doc-type', 'index': MATCH}, 'filename'),
State({'type': 'upload-doc-type', 'index': MATCH}, 'id')
)
def update_uploaded_doc_name(contents, filename, id_dict):
if contents is not None:
uploaded_doc_contents[id_dict['index']] = (contents, filename)
logging.info(f"{id_dict['index']} file uploaded: {filename}")
return filename, contents
return "", None
@app.callback(
Output('document-preview', 'children', allow_duplicate=True),
Output('loading-output', 'children', allow_duplicate=True),
Output('status-bar', 'children', allow_duplicate=True),
Input({'type': 'btn-generate-doc', 'index': ALL}, 'n_clicks'),
State({'type': 'btn-generate-doc', 'index': ALL}, 'id'),
State({'type': 'radio-doc-source', 'index': ALL}, 'value'),
State({'type': 'upload-doc-type', 'index': ALL}, 'contents'),
State({'type': 'upload-doc-type', 'index': ALL}, 'filename'),
prevent_initial_call=True
)
def generate_other_doc(n_clicks_list, btn_ids, radio_values, upload_contents, upload_filenames):
global current_document, document_type, shredded_document, pink_review_document
ctx = callback_context
if not ctx.triggered:
raise dash.exceptions.PreventUpdate
idx = [i for i, x in enumerate(n_clicks_list) if x]
if not idx:
raise dash.exceptions.PreventUpdate
idx = idx[-1]
doc_type = btn_ids[idx]['index']
document_type = doc_type
if doc_type == "Shred":
raise dash.exceptions.PreventUpdate
if shredded_document is None:
return html.Div("Please shred a document first."), "", "Please shred a document first."
source = radio_values[idx] if radio_values and len(radio_values) > idx else 'loaded'
doc_content = None
if source == 'uploaded':
if upload_contents and len(upload_contents) > idx and upload_contents[idx] and upload_filenames and len(upload_filenames) > idx and upload_filenames[idx]:
doc_content = process_document(upload_contents[idx], upload_filenames[idx])
else:
return html.Div("Please upload a document to use as source."), "", "Please upload a document to use as source."
else:
if doc_type == "Pink":
doc_content = shredded_document
elif doc_type == "Pink Review":
doc_content = pink_review_document if pink_review_document else ""
elif doc_type == "Red":
doc_content = pink_review_document if pink_review_document else ""
elif doc_type == "Red Review":
doc_content = pink_review_document if pink_review_document else ""
elif doc_type == "Gold":
doc_content = shredded_document
elif doc_type == "Gold Review":
doc_content = shredded_document
elif doc_type == "Virtual Board":
doc_content = shredded_document
elif doc_type == "LOE":
doc_content = shredded_document
else:
doc_content = shredded_document
try:
if doc_type == "Pink Review":
current_document = generate_document(doc_type, [doc_content, shredded_document])
pink_review_document = current_document
elif doc_type in ["Red", "Red Review"]:
current_document = generate_document(doc_type, [doc_content, shredded_document])
else:
current_document = generate_document(doc_type, [doc_content])
logging.info(f"{doc_type} document generated successfully.")
return dcc.Markdown(current_document), f"{doc_type} generated", f"{doc_type} document generated successfully."
except Exception as e:
logging.error(f"Error generating document: {str(e)}")
return html.Div(f"Error generating document: {str(e)}"), "Error", "An error occurred while generating the document."
@app.callback(
Output('chat-output', 'children'),
Output('document-preview', 'children', allow_duplicate=True),
Input('btn-send-chat', 'n_clicks'),
State('chat-input', 'value'),
prevent_initial_call=True
)
def update_document_via_chat(n_clicks, chat_input):
global current_document, document_type
if not chat_input or current_document is None:
raise dash.exceptions.PreventUpdate
prompt = f"""Update the following {document_type} based on this instruction: {chat_input}
Current document:
{current_document}
Instructions:
1. Provide the updated document content.
2. Maintain proper formatting and structure.
3. Incorporate the requested changes seamlessly.
Now, provide the updated {document_type}:
"""
logging.info(f"Updating document via chat for {document_type} instruction: {chat_input}")
try:
response = openai.ChatCompletion.create(
model="gpt-4-1106-preview",
messages=[
{"role": "system", "content": "You are a helpful, expert government proposal writer."},
{"role": "user", "content": prompt}
],
max_tokens=4096,
temperature=0.2,
)
current_document = response['choices'][0]['message']['content']
logging.info("Document updated via chat successfully.")
return f"Document updated based on: {chat_input}", dcc.Markdown(current_document)
except Exception as e:
logging.error(f"Error updating document via chat: {str(e)}")
return f"Error updating document: {str(e)}", html.Div(f"Error updating document: {str(e)}")
@app.callback(
Output("download-document", "data"),
Input("btn-download", "n_clicks"),
prevent_initial_call=True
)
def download_document(n_clicks):
global current_document, document_type
if current_document is None:
raise dash.exceptions.PreventUpdate
if document_type == "LOE":
try:
df = pd.read_csv(StringIO(current_document))
output = BytesIO()
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
df.to_excel(writer, sheet_name='LOE', index=False)
logging.info("LOE document downloaded as Excel.")
return dcc.send_bytes(output.getvalue(), f"{document_type}.xlsx")
except Exception as e:
logging.error(f"Error downloading LOE document: {str(e)}")
return dcc.send_string(f"Error downloading LOE: {str(e)}", f"{document_type}_error.txt")
else:
try:
doc = Document()
doc.add_paragraph(current_document)
output = BytesIO()
doc.save(output)
logging.info("Document downloaded as Word.")
return dcc.send_bytes(output.getvalue(), f"{document_type}.docx")
except Exception as e:
logging.error(f"Error downloading document: {str(e)}")
return dcc.send_string(f"Error downloading document: {str(e)}", f"{document_type}_error.txt")
if __name__ == '__main__':
print("Starting the Dash application...")
app.run(debug=True, host='0.0.0.0', port=7860, threaded=True)
print("Dash application has finished running.") |