Spaces:
Paused
Paused
Update app.py via AI Editor
Browse files
app.py
CHANGED
@@ -1,494 +1 @@
|
|
1 |
-
|
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 logging
|
14 |
-
import threading
|
15 |
-
import requests
|
16 |
-
import json
|
17 |
-
|
18 |
-
logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s %(message)s')
|
19 |
-
|
20 |
-
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP], suppress_callback_exceptions=True)
|
21 |
-
|
22 |
-
ANTHROPIC_API_URL = "https://api.anthropic.com/v1/messages"
|
23 |
-
ANTHROPIC_API_KEY = os.getenv("ANTHROPIC_API_KEY", "YOUR_ANTHROPIC_API_KEY")
|
24 |
-
|
25 |
-
uploaded_files = {}
|
26 |
-
current_document = None
|
27 |
-
document_type = None
|
28 |
-
shredded_document = None
|
29 |
-
pink_review_document = None
|
30 |
-
uploaded_doc_contents = {}
|
31 |
-
|
32 |
-
document_types = {
|
33 |
-
"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",
|
34 |
-
"Pink": "Create a Pink Team document based on the PWS outline. Your goal is to be compliant and compelling.",
|
35 |
-
"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",
|
36 |
-
"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",
|
37 |
-
"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",
|
38 |
-
"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",
|
39 |
-
"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",
|
40 |
-
"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",
|
41 |
-
"LOE": "Generate a Level of Effort (LOE) breakdown as a spreadsheet"
|
42 |
-
}
|
43 |
-
|
44 |
-
def get_right_col_content(selected_type):
|
45 |
-
if selected_type == "Shred":
|
46 |
-
return [
|
47 |
-
html.Div([
|
48 |
-
html.Div(className="blinking-dot", style={'margin':'0 auto','width':'16px','height':'16px'}),
|
49 |
-
], style={'textAlign':'center', 'marginBottom':'10px'}),
|
50 |
-
dcc.Loading(
|
51 |
-
id="loading-indicator",
|
52 |
-
type="dot",
|
53 |
-
children=[html.Div(id="loading-output")]
|
54 |
-
),
|
55 |
-
html.Div(id='document-preview', className="border p-3 mb-3"),
|
56 |
-
dbc.Button("Download Document", id="btn-download", color="success", className="mt-3"),
|
57 |
-
dcc.Download(id="download-document"),
|
58 |
-
html.Hr(),
|
59 |
-
dcc.Loading(
|
60 |
-
id="chat-loading",
|
61 |
-
type="dot",
|
62 |
-
children=[
|
63 |
-
dbc.Input(id="chat-input", type="text", placeholder="Chat with AI to update document...", className="mb-2", style={'whiteSpace':'pre-wrap'}),
|
64 |
-
dbc.Button("Send", id="btn-send-chat", color="primary", className="mb-3"),
|
65 |
-
html.Div(id="chat-output")
|
66 |
-
]
|
67 |
-
)
|
68 |
-
]
|
69 |
-
else:
|
70 |
-
return [
|
71 |
-
html.Div([
|
72 |
-
html.Div(className="blinking-dot", style={'margin':'0 auto','width':'16px','height':'16px'}),
|
73 |
-
], style={'textAlign':'center', 'marginBottom':'10px'}),
|
74 |
-
dcc.Loading(
|
75 |
-
id="loading-indicator",
|
76 |
-
type="dot",
|
77 |
-
children=[html.Div(id="loading-output")]
|
78 |
-
),
|
79 |
-
html.Div(id='document-preview', className="border p-3 mb-3"),
|
80 |
-
dbc.Button("Download Document", id="btn-download", color="success", className="mt-3"),
|
81 |
-
dcc.Download(id="download-document"),
|
82 |
-
html.Hr(),
|
83 |
-
html.Div([
|
84 |
-
html.Label(f"Upload {selected_type} Document"),
|
85 |
-
dcc.Upload(
|
86 |
-
id={'type': 'upload-doc-type', 'index': selected_type},
|
87 |
-
children=html.Div(['Drag and Drop or ', html.A('Select File')]),
|
88 |
-
style={
|
89 |
-
'width': '100%',
|
90 |
-
'height': '60px',
|
91 |
-
'lineHeight': '60px',
|
92 |
-
'borderWidth': '1px',
|
93 |
-
'borderStyle': 'dashed',
|
94 |
-
'borderRadius': '5px',
|
95 |
-
'textAlign': 'center',
|
96 |
-
'margin': '10px 0'
|
97 |
-
},
|
98 |
-
multiple=False
|
99 |
-
),
|
100 |
-
html.Div(id={'type': 'uploaded-doc-name', 'index': selected_type}),
|
101 |
-
dbc.RadioItems(
|
102 |
-
id={'type': 'radio-doc-source', 'index': selected_type},
|
103 |
-
options=[
|
104 |
-
{'label': 'Loaded Document', 'value': 'loaded'},
|
105 |
-
{'label': 'Uploaded Document', 'value': 'uploaded'}
|
106 |
-
],
|
107 |
-
value='loaded',
|
108 |
-
inline=True,
|
109 |
-
className="mb-2"
|
110 |
-
),
|
111 |
-
dbc.Button("Generate Document", id={'type': 'btn-generate-doc', 'index': selected_type}, color="primary", className="mb-3"),
|
112 |
-
], id={'type': 'doc-type-controls', 'index': selected_type}),
|
113 |
-
dcc.Loading(
|
114 |
-
id="chat-loading",
|
115 |
-
type="dot",
|
116 |
-
children=[
|
117 |
-
dbc.Input(id="chat-input", type="text", placeholder="Chat with AI to update document...", className="mb-2", style={'whiteSpace':'pre-wrap'}),
|
118 |
-
dbc.Button("Send", id="btn-send-chat", color="primary", className="mb-3"),
|
119 |
-
html.Div(id="chat-output")
|
120 |
-
]
|
121 |
-
)
|
122 |
-
]
|
123 |
-
|
124 |
-
app.layout = dbc.Container([
|
125 |
-
dbc.Row([
|
126 |
-
dbc.Col([
|
127 |
-
html.H4("Proposal Documents", className="mt-3 mb-4"),
|
128 |
-
html.Div([
|
129 |
-
html.Div(className="blinking-dot", style={'margin':'0 auto','width':'16px','height':'16px'}),
|
130 |
-
], style={'textAlign':'center', 'marginBottom':'10px'}),
|
131 |
-
dcc.Upload(
|
132 |
-
id='upload-document',
|
133 |
-
children=html.Div([
|
134 |
-
'Drag and Drop or ',
|
135 |
-
html.A('Select Files')
|
136 |
-
]),
|
137 |
-
style={
|
138 |
-
'width': '100%',
|
139 |
-
'height': '60px',
|
140 |
-
'lineHeight': '60px',
|
141 |
-
'borderWidth': '1px',
|
142 |
-
'borderStyle': 'dashed',
|
143 |
-
'borderRadius': '5px',
|
144 |
-
'textAlign': 'center',
|
145 |
-
'margin': '10px 0'
|
146 |
-
},
|
147 |
-
multiple=True
|
148 |
-
),
|
149 |
-
html.Div(id='file-list'),
|
150 |
-
html.Hr(),
|
151 |
-
html.Div([
|
152 |
-
dbc.Button(
|
153 |
-
doc_type,
|
154 |
-
id={'type': 'btn-doc-type', 'index': doc_type},
|
155 |
-
color="link",
|
156 |
-
className="mb-2 w-100 text-left custom-button",
|
157 |
-
style={'overflow': 'hidden', 'text-overflow': 'ellipsis', 'white-space': 'nowrap'}
|
158 |
-
) for doc_type in document_types.keys()
|
159 |
-
])
|
160 |
-
], width=3),
|
161 |
-
dbc.Col([
|
162 |
-
html.Div(id='right-col-content')
|
163 |
-
], width=9)
|
164 |
-
])
|
165 |
-
], fluid=True)
|
166 |
-
|
167 |
-
def process_document(contents, filename):
|
168 |
-
content_type, content_string = contents.split(',')
|
169 |
-
decoded = base64.b64decode(content_string)
|
170 |
-
try:
|
171 |
-
if filename.lower().endswith('.docx'):
|
172 |
-
doc = Document(BytesIO(decoded))
|
173 |
-
text = "\n".join([para.text for para in doc.paragraphs])
|
174 |
-
return text
|
175 |
-
elif filename.lower().endswith('.pdf'):
|
176 |
-
pdf = PdfReader(BytesIO(decoded))
|
177 |
-
text = ""
|
178 |
-
for page in pdf.pages:
|
179 |
-
page_text = page.extract_text()
|
180 |
-
if page_text:
|
181 |
-
text += page_text
|
182 |
-
return text
|
183 |
-
else:
|
184 |
-
return f"Unsupported file format: {filename}. Please upload a PDF or DOCX file."
|
185 |
-
except Exception as e:
|
186 |
-
logging.error(f"Error processing document: {str(e)}")
|
187 |
-
return f"Error processing document: {str(e)}"
|
188 |
-
|
189 |
-
@app.callback(
|
190 |
-
Output('file-list', 'children'),
|
191 |
-
Input('upload-document', 'contents'),
|
192 |
-
State('upload-document', 'filename'),
|
193 |
-
State('file-list', 'children')
|
194 |
-
)
|
195 |
-
def update_output(list_of_contents, list_of_names, existing_files):
|
196 |
-
global uploaded_files, shredded_document
|
197 |
-
if list_of_contents is not None:
|
198 |
-
new_files = []
|
199 |
-
for i, (content, name) in enumerate(zip(list_of_contents, list_of_names)):
|
200 |
-
file_content = process_document(content, name)
|
201 |
-
uploaded_files[name] = file_content
|
202 |
-
new_files.append(html.Div([
|
203 |
-
html.Button('×', id={'type': 'remove-file', 'index': name}, style={'marginRight': '5px', 'fontSize': '10px'}),
|
204 |
-
html.Span(name)
|
205 |
-
]))
|
206 |
-
if existing_files is None:
|
207 |
-
existing_files = []
|
208 |
-
shredded_document = None
|
209 |
-
logging.info("Documents uploaded and file list updated.")
|
210 |
-
return existing_files + new_files
|
211 |
-
return existing_files
|
212 |
-
|
213 |
-
@app.callback(
|
214 |
-
Output('file-list', 'children', allow_duplicate=True),
|
215 |
-
Input({'type': 'remove-file', 'index': ALL}, 'n_clicks'),
|
216 |
-
State('file-list', 'children'),
|
217 |
-
prevent_initial_call=True
|
218 |
-
)
|
219 |
-
def remove_file(n_clicks, existing_files):
|
220 |
-
global uploaded_files, shredded_document
|
221 |
-
ctx = dash.callback_context
|
222 |
-
if not ctx.triggered:
|
223 |
-
raise dash.exceptions.PreventUpdate
|
224 |
-
removed_file = ctx.triggered[0]['prop_id'].split(',')[0].split(':')[-1].strip('}')
|
225 |
-
uploaded_files.pop(removed_file, None)
|
226 |
-
shredded_document = None
|
227 |
-
logging.info(f"Removed file: {removed_file}")
|
228 |
-
return [file for file in existing_files if file['props']['children'][1]['props']['children'] != removed_file]
|
229 |
-
|
230 |
-
@app.callback(
|
231 |
-
Output('right-col-content', 'children'),
|
232 |
-
[Input({'type': 'btn-doc-type', 'index': ALL}, 'n_clicks')],
|
233 |
-
[State({'type': 'btn-doc-type', 'index': ALL}, 'id')]
|
234 |
-
)
|
235 |
-
def update_right_col(n_clicks_list, btn_ids):
|
236 |
-
triggered = callback_context.triggered
|
237 |
-
if not triggered or all(x is None for x in n_clicks_list):
|
238 |
-
selected_type = "Shred"
|
239 |
-
else:
|
240 |
-
idx = [i for i, x in enumerate(n_clicks_list) if x]
|
241 |
-
if idx:
|
242 |
-
selected_type = btn_ids[idx[-1]]['index']
|
243 |
-
else:
|
244 |
-
selected_type = "Shred"
|
245 |
-
return get_right_col_content(selected_type)
|
246 |
-
|
247 |
-
def anthropic_generate(prompt, model="claude-3-opus-20240229", max_tokens=4096, temperature=0.25):
|
248 |
-
headers = {
|
249 |
-
"x-api-key": ANTHROPIC_API_KEY,
|
250 |
-
"anthropic-version": "2023-06-01",
|
251 |
-
"content-type": "application/json"
|
252 |
-
}
|
253 |
-
data = {
|
254 |
-
"model": model,
|
255 |
-
"max_tokens": max_tokens,
|
256 |
-
"temperature": temperature,
|
257 |
-
"messages": [
|
258 |
-
{"role": "user", "content": prompt},
|
259 |
-
],
|
260 |
-
}
|
261 |
-
try:
|
262 |
-
response = requests.post(ANTHROPIC_API_URL, headers=headers, data=json.dumps(data), timeout=120)
|
263 |
-
response.raise_for_status()
|
264 |
-
result = response.json()
|
265 |
-
if "content" in result and isinstance(result["content"], list):
|
266 |
-
content = ""
|
267 |
-
for item in result["content"]:
|
268 |
-
if isinstance(item, dict) and "text" in item:
|
269 |
-
content += item["text"]
|
270 |
-
elif isinstance(item, str):
|
271 |
-
content += item
|
272 |
-
return content
|
273 |
-
elif "content" in result and isinstance(result["content"], str):
|
274 |
-
return result["content"]
|
275 |
-
elif "stop_reason" in result and "output" in result:
|
276 |
-
return result["output"]
|
277 |
-
else:
|
278 |
-
raise Exception(f"Anthropic API unexpected response: {result}")
|
279 |
-
except Exception as e:
|
280 |
-
logging.error(f"Anthropic API error: {str(e)}")
|
281 |
-
raise
|
282 |
-
|
283 |
-
def generate_document(document_type, file_contents):
|
284 |
-
prompt = f"""Generate a {document_type} based on the following project artifacts:
|
285 |
-
{' '.join(file_contents)}
|
286 |
-
Instructions:
|
287 |
-
1. Create the {document_type} as a detailed document.
|
288 |
-
2. Use proper formatting and structure.
|
289 |
-
3. Include all necessary sections and details.
|
290 |
-
4. Start the output immediately with the document content.
|
291 |
-
5. IMPORTANT: If the document type is Pink, Red, Gold and not
|
292 |
-
Pink Review, Red Review, Gold Review, or spreadsheet, loe or virtual board
|
293 |
-
then your goal is to be compliant and compelling based on the
|
294 |
-
requrements, write in paragraph in active voice as
|
295 |
-
MicroHealth, limit bullets, answer the
|
296 |
-
requirement with what MicroHealth will do
|
297 |
-
to satisfy the requirement, the technical
|
298 |
-
approach with innovation for efficiency,
|
299 |
-
productivity, quality and measurable
|
300 |
-
outcomes, the industry standard that
|
301 |
-
methodology is based on if applicable,
|
302 |
-
detail the workflow or steps to accomplish
|
303 |
-
the requirement with labor categories that
|
304 |
-
will do those tasks in that workflow,
|
305 |
-
reference reputable research like gartner,
|
306 |
-
forrester, IDC, Deloitte, Accenture etc
|
307 |
-
with measures of success and substantiation
|
308 |
-
of MicroHealth's approach. Never use soft words
|
309 |
-
like maybe, could be, should, possible be definitive in your language and confident.
|
310 |
-
6. you must also take into account section L&M of the document which is the evaluation criteria
|
311 |
-
to be sure we address them.
|
312 |
-
Now, generate the {document_type}:
|
313 |
-
"""
|
314 |
-
logging.info(f"Generating document for type: {document_type}")
|
315 |
-
try:
|
316 |
-
generated_text = anthropic_generate(prompt)
|
317 |
-
logging.info("Document generated successfully.")
|
318 |
-
return generated_text
|
319 |
-
except Exception as e:
|
320 |
-
logging.error(f"Error generating document: {str(e)}")
|
321 |
-
raise
|
322 |
-
|
323 |
-
@app.callback(
|
324 |
-
Output('document-preview', 'children'),
|
325 |
-
Output('loading-output', 'children'),
|
326 |
-
Input({'type': 'btn-doc-type', 'index': 'Shred'}, 'n_clicks'),
|
327 |
-
prevent_initial_call=True
|
328 |
-
)
|
329 |
-
def generate_shred_doc(n_clicks):
|
330 |
-
global current_document, document_type, shredded_document
|
331 |
-
if not uploaded_files:
|
332 |
-
return html.Div("Please upload a document before shredding."), ""
|
333 |
-
file_contents = list(uploaded_files.values())
|
334 |
-
try:
|
335 |
-
shredded_document = generate_document("Shred", file_contents)
|
336 |
-
current_document = shredded_document
|
337 |
-
return dcc.Markdown(shredded_document), "Shred generated"
|
338 |
-
except Exception as e:
|
339 |
-
logging.error(f"Error generating document: {str(e)}")
|
340 |
-
return html.Div(f"Error generating document: {str(e)}"), "Error"
|
341 |
-
|
342 |
-
@app.callback(
|
343 |
-
Output({'type': 'uploaded-doc-name', 'index': MATCH}, 'children'),
|
344 |
-
Output({'type': 'upload-doc-type', 'index': MATCH}, 'contents'),
|
345 |
-
Input({'type': 'upload-doc-type', 'index': MATCH}, 'contents'),
|
346 |
-
State({'type': 'upload-doc-type', 'index': MATCH}, 'filename'),
|
347 |
-
State({'type': 'upload-doc-type', 'index': MATCH}, 'id')
|
348 |
-
)
|
349 |
-
def update_uploaded_doc_name(contents, filename, id_dict):
|
350 |
-
if contents is not None:
|
351 |
-
uploaded_doc_contents[id_dict['index']] = (contents, filename)
|
352 |
-
logging.info(f"{id_dict['index']} file uploaded: {filename}")
|
353 |
-
return filename, contents
|
354 |
-
return "", None
|
355 |
-
|
356 |
-
@app.callback(
|
357 |
-
Output('document-preview', 'children', allow_duplicate=True),
|
358 |
-
Output('loading-output', 'children', allow_duplicate=True),
|
359 |
-
Input({'type': 'btn-generate-doc', 'index': ALL}, 'n_clicks'),
|
360 |
-
State({'type': 'btn-generate-doc', 'index': ALL}, 'id'),
|
361 |
-
State({'type': 'radio-doc-source', 'index': ALL}, 'value'),
|
362 |
-
State({'type': 'upload-doc-type', 'index': ALL}, 'contents'),
|
363 |
-
State({'type': 'upload-doc-type', 'index': ALL}, 'filename'),
|
364 |
-
prevent_initial_call=True
|
365 |
-
)
|
366 |
-
def generate_other_doc(n_clicks_list, btn_ids, radio_values, upload_contents, upload_filenames):
|
367 |
-
global current_document, document_type, shredded_document, pink_review_document
|
368 |
-
ctx = callback_context
|
369 |
-
if not ctx.triggered:
|
370 |
-
raise dash.exceptions.PreventUpdate
|
371 |
-
idx = [i for i, x in enumerate(n_clicks_list) if x]
|
372 |
-
if not idx:
|
373 |
-
raise dash.exceptions.PreventUpdate
|
374 |
-
idx = idx[-1]
|
375 |
-
doc_type = btn_ids[idx]['index']
|
376 |
-
document_type = doc_type
|
377 |
-
|
378 |
-
if doc_type == "Shred":
|
379 |
-
raise dash.exceptions.PreventUpdate
|
380 |
-
|
381 |
-
if shredded_document is None:
|
382 |
-
return html.Div("Please shred a document first."), ""
|
383 |
-
|
384 |
-
source = radio_values[idx] if radio_values and len(radio_values) > idx else 'loaded'
|
385 |
-
doc_content = None
|
386 |
-
|
387 |
-
if source == 'uploaded':
|
388 |
-
if upload_contents and len(upload_contents) > idx and upload_contents[idx] and upload_filenames and len(upload_filenames) > idx and upload_filenames[idx]:
|
389 |
-
doc_content = process_document(upload_contents[idx], upload_filenames[idx])
|
390 |
-
else:
|
391 |
-
return html.Div("Please upload a document to use as source."), ""
|
392 |
-
else:
|
393 |
-
if doc_type == "Pink":
|
394 |
-
doc_content = shredded_document
|
395 |
-
elif doc_type == "Pink Review":
|
396 |
-
doc_content = pink_review_document if pink_review_document else ""
|
397 |
-
elif doc_type == "Red":
|
398 |
-
doc_content = pink_review_document if pink_review_document else ""
|
399 |
-
elif doc_type == "Red Review":
|
400 |
-
doc_content = pink_review_document if pink_review_document else ""
|
401 |
-
elif doc_type == "Gold":
|
402 |
-
doc_content = shredded_document
|
403 |
-
elif doc_type == "Gold Review":
|
404 |
-
doc_content = shredded_document
|
405 |
-
elif doc_type == "Virtual Board":
|
406 |
-
doc_content = shredded_document
|
407 |
-
elif doc_type == "LOE":
|
408 |
-
doc_content = shredded_document
|
409 |
-
else:
|
410 |
-
doc_content = shredded_document
|
411 |
-
|
412 |
-
try:
|
413 |
-
if doc_type == "Pink Review":
|
414 |
-
current_document = generate_document(doc_type, [doc_content, shredded_document])
|
415 |
-
pink_review_document = current_document
|
416 |
-
elif doc_type in ["Red", "Red Review"]:
|
417 |
-
current_document = generate_document(doc_type, [doc_content, shredded_document])
|
418 |
-
else:
|
419 |
-
current_document = generate_document(doc_type, [doc_content])
|
420 |
-
logging.info(f"{doc_type} document generated successfully.")
|
421 |
-
return dcc.Markdown(current_document), f"{doc_type} generated"
|
422 |
-
except Exception as e:
|
423 |
-
logging.error(f"Error generating document: {str(e)}")
|
424 |
-
return html.Div(f"Error generating document: {str(e)}"), "Error"
|
425 |
-
|
426 |
-
@app.callback(
|
427 |
-
Output('chat-output', 'children'),
|
428 |
-
Output('document-preview', 'children', allow_duplicate=True),
|
429 |
-
Input('btn-send-chat', 'n_clicks'),
|
430 |
-
State('chat-input', 'value'),
|
431 |
-
prevent_initial_call=True
|
432 |
-
)
|
433 |
-
def update_document_via_chat(n_clicks, chat_input):
|
434 |
-
global current_document, document_type
|
435 |
-
if not chat_input or current_document is None:
|
436 |
-
raise dash.exceptions.PreventUpdate
|
437 |
-
|
438 |
-
prompt = f"""Update the following {document_type} based on this instruction: {chat_input}
|
439 |
-
Current document:
|
440 |
-
{current_document}
|
441 |
-
Instructions:
|
442 |
-
1. Provide the updated document content.
|
443 |
-
2. Maintain proper formatting and structure.
|
444 |
-
3. Incorporate the requested changes seamlessly.
|
445 |
-
Now, provide the updated {document_type}:
|
446 |
-
"""
|
447 |
-
|
448 |
-
logging.info(f"Updating document via chat for {document_type} instruction: {chat_input}")
|
449 |
-
try:
|
450 |
-
updated_content = anthropic_generate(prompt, temperature=0.2)
|
451 |
-
current_document = updated_content
|
452 |
-
logging.info("Document updated via chat successfully.")
|
453 |
-
return f"Document updated based on: {chat_input}", dcc.Markdown(current_document)
|
454 |
-
except Exception as e:
|
455 |
-
logging.error(f"Error updating document via chat: {str(e)}")
|
456 |
-
return f"Error updating document: {str(e)}", html.Div(f"Error updating document: {str(e)}")
|
457 |
-
|
458 |
-
@app.callback(
|
459 |
-
Output("download-document", "data"),
|
460 |
-
Input("btn-download", "n_clicks"),
|
461 |
-
prevent_initial_call=True
|
462 |
-
)
|
463 |
-
def download_document(n_clicks):
|
464 |
-
global current_document, document_type
|
465 |
-
if current_document is None:
|
466 |
-
raise dash.exceptions.PreventUpdate
|
467 |
-
|
468 |
-
if document_type == "LOE":
|
469 |
-
try:
|
470 |
-
df = pd.read_csv(StringIO(current_document))
|
471 |
-
output = BytesIO()
|
472 |
-
with pd.ExcelWriter(output, engine='xlsxwriter') as writer:
|
473 |
-
df.to_excel(writer, sheet_name='LOE', index=False)
|
474 |
-
logging.info("LOE document downloaded as Excel.")
|
475 |
-
return dcc.send_bytes(output.getvalue(), f"{document_type}.xlsx")
|
476 |
-
except Exception as e:
|
477 |
-
logging.error(f"Error downloading LOE document: {str(e)}")
|
478 |
-
return dcc.send_string(f"Error downloading LOE: {str(e)}", f"{document_type}_error.txt")
|
479 |
-
else:
|
480 |
-
try:
|
481 |
-
doc = Document()
|
482 |
-
doc.add_paragraph(current_document)
|
483 |
-
output = BytesIO()
|
484 |
-
doc.save(output)
|
485 |
-
logging.info("Document downloaded as Word.")
|
486 |
-
return dcc.send_bytes(output.getvalue(), f"{document_type}.docx")
|
487 |
-
except Exception as e:
|
488 |
-
logging.error(f"Error downloading document: {str(e)}")
|
489 |
-
return dcc.send_string(f"Error downloading document: {str(e)}", f"{document_type}_error.txt")
|
490 |
-
|
491 |
-
if __name__ == '__main__':
|
492 |
-
print("Starting the Dash application...")
|
493 |
-
app.run(debug=True, host='0.0.0.0', port=7860, threaded=True)
|
494 |
-
print("Dash application has finished running.")
|
|
|
1 |
+
—
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|