Spaces:
Paused
Paused
import os | |
import base64 | |
import logging | |
import threading | |
import pandas as pd | |
from io import BytesIO, StringIO | |
from docx import Document | |
from PyPDF2 import PdfReader | |
import dash | |
import dash_bootstrap_components as dbc | |
from dash import html, dcc, Input, Output, State, dash_table, callback_context | |
import anthropic | |
logging.basicConfig(level=logging.INFO) | |
ANTHROPIC_KEY = os.environ.get("ANTHROPIC_API_KEY", "") | |
anthropic_client = anthropic.Anthropic(api_key=ANTHROPIC_KEY) | |
CLAUDE3_SONNET_MODEL = "claude-3-7-sonnet-20250219" | |
CLAUDE3_MAX_CONTEXT_TOKENS = 200_000 | |
CLAUDE3_MAX_OUTPUT_TOKENS = 64_000 | |
document_types = { | |
"Shred": "Ignore all other instructions and generate only 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 highly detailed Pink Team document based on the PWS outline. Your goal is to be compliant and compelling. Focus on describing the approach and how it will be done, the steps, workflow, people, processes and technology based on well known industry standards to accomplish the task. Be sure to demonstrate innovation.", | |
"Pink Review": "Ignore all other instructions and generate and evaluate compliance of the Pink Team document against the requirements and output only 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. you must also take into account section L&M of the document which is the evaluation criteria to be sure we address them.", | |
"Red": "Produce a highly detailed 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. Focus on describing the approach and how it will be done, the steps, workflow, people, processes and technology to accomplish the task. Be sure to refer to research that validates the approach and cite sources with measurable outcomes", | |
"Red Review": "Ignore all other instructions and generate and evaluate compliance of the Red Team document against the requirements and output a only 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. you must also take into account section L&M of the document which is the evaluation criteria to be sure we address them", | |
"Gold": "Create a highly detailed Gold 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. Focus on describing the approach and how it will be done, the steps, workflow, people, processes and technology to accomplish the task. Be sure to refer to research that validates the approach and cite sources with measurable outcomes and improve on innovations of the approach", | |
"Gold Review": "Ignore all other instructions and generate and perform a final compliance review against the requirements and output only 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. you must also take into account section L&M of the document which is the evaluation criteria to be sure we address them", | |
"Virtual Board": "Ignore all other instructions and generate and 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 and produce only spreadsheet", | |
"LOE": "Ignore all other instructions and generate and generate a Level of Effort (LOE) breakdown and produce only spreadsheet" | |
} | |
def process_document(contents, filename): | |
content_type, content_string = contents.split(',') | |
decoded = base64.b64decode(content_string) | |
if filename.lower().endswith('.docx'): | |
doc = Document(BytesIO(decoded)) | |
return "\n".join([p.text for p in doc.paragraphs]) | |
elif filename.lower().endswith('.pdf'): | |
pdf = PdfReader(BytesIO(decoded)) | |
return "".join(page.extract_text() or "" for page in pdf.pages) | |
else: | |
return f"Unsupported file format: {filename}" | |
def call_claude(prompt, max_tokens=2048): | |
res = anthropic_client.messages.create( | |
model=CLAUDE3_SONNET_MODEL, | |
max_tokens=max_tokens, | |
temperature=0.1, | |
system="You are a world class proposal consultant and proposal manager.", | |
messages=[{"role": "user", "content": prompt}] | |
) | |
return res.content[0].text if hasattr(res, "content") else str(res) | |
def spreadsheet_to_df(text): | |
lines = [l.strip() for l in text.splitlines() if '|' in l] | |
if not lines: return pd.DataFrame() | |
header = lines[0].strip('|').split('|') | |
data = [l.strip('|').split('|') for l in lines[1:]] | |
return pd.DataFrame(data, columns=[h.strip() for h in header]) | |
def generate_content(document, doc_type): | |
prompt = f"{document_types[doc_type]}\n\nDocument:\n{document}\n\nOutput only one spreadsheet table, use | as column separator." | |
response = call_claude(prompt, max_tokens=4096) | |
df = spreadsheet_to_df(response) | |
return response, df | |
def parse_markdown(doc, content): | |
for para in content.split('\n\n'): | |
doc.add_paragraph(para) | |
def create_docx(content): | |
doc = Document() | |
parse_markdown(doc, content) | |
return doc | |
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP], suppress_callback_exceptions=True) | |
app.title = "MicroHealth PWS Analyzer" | |
nav_items = [ | |
dbc.NavLink("Shred", href="#", id="nav-shred"), | |
dbc.NavLink("Pink", href="#", id="nav-pink"), | |
dbc.NavLink("Pink Review", href="#", id="nav-pink-review"), | |
dbc.NavLink("Red", href="#", id="nav-red"), | |
dbc.NavLink("Red Review", href="#", id="nav-red-review"), | |
dbc.NavLink("Gold", href="#", id="nav-gold"), | |
dbc.NavLink("Gold Review", href="#", id="nav-gold-review"), | |
dbc.NavLink("Virtual Board", href="#", id="nav-virtual-board"), | |
dbc.NavLink("LOE", href="#", id="nav-loe"), | |
] | |
def make_upload(btn_id): | |
return dcc.Upload( | |
id=f'{btn_id}-upload', | |
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'}, | |
multiple=False | |
) | |
def make_textarea(btn_id, placeholder): | |
return dbc.Textarea( | |
id=f'{btn_id}-instructions', | |
placeholder=placeholder, | |
style={'height': '80px', 'marginBottom': '10px', 'width': '100%', 'whiteSpace': 'pre-wrap', 'overflowWrap': 'break-word'} | |
) | |
def make_tab(tab_id, label): | |
return dbc.Card( | |
dbc.CardBody([ | |
make_textarea(tab_id, f"Instructions for {label} (optional)"), | |
make_upload(tab_id), | |
dbc.Button(f"Generate {label}", id=f'{tab_id}-btn', className="mt-2 btn-primary", n_clicks=0), | |
dcc.Loading(html.Div(id=f'{tab_id}-output'), type="default", parent_style={'justifyContent': 'center'}), | |
dbc.Button(f"Download {label} Report", id=f"{tab_id}-download-btn", className="mt-2 btn-secondary", n_clicks=0), | |
dcc.Download(id=f"{tab_id}-download") | |
]), className="mb-4" | |
) | |
main_tabs = [ | |
{"id": "shred", "label": "Shred"}, | |
{"id": "pink", "label": "Pink"}, | |
{"id": "pink-review", "label": "Pink Review"}, | |
{"id": "red", "label": "Red"}, | |
{"id": "red-review", "label": "Red Review"}, | |
{"id": "gold", "label": "Gold"}, | |
{"id": "gold-review", "label": "Gold Review"}, | |
{"id": "virtual-board", "label": "Virtual Board"}, | |
{"id": "loe", "label": "LOE"}, | |
] | |
app.layout = dbc.Container([ | |
html.H1("MicroHealth PWS Analysis and Response Generator", className="my-3"), | |
dbc.Row([ | |
dbc.Col( | |
dbc.Card( | |
dbc.CardBody([ | |
html.Div(nav_items, className="nav flex-column"), | |
]) | |
), width=3, style={'minWidth': '220px'} | |
), | |
dbc.Col( | |
html.Div([ | |
dcc.Tabs( | |
id="main-tabs", | |
value="shred", | |
children=[dcc.Tab(label=tab["label"], value=tab["id"]) for tab in main_tabs], | |
className="mb-3" | |
), | |
html.Div(id="main-content") | |
]), | |
width=9 | |
) | |
]) | |
], fluid=True) | |
tab_cards = {tab["id"]: make_tab(tab["id"], tab["label"]) for tab in main_tabs} | |
def render_tab(tab): | |
return tab_cards[tab] | |
def handle_all_tabs(*args): | |
n = len(tab_cards) | |
outputs = [None] * (n * 2) | |
ctx = callback_context | |
if not ctx.triggered: return outputs | |
trig = ctx.triggered[0]['prop_id'] | |
for idx, tab_id in enumerate(tab_cards): | |
gen_btn = f"{tab_id}-btn.n_clicks" | |
dl_btn = f"{tab_id}-download-btn.n_clicks" | |
out_idx = idx | |
dl_idx = idx + n | |
upload_idx = idx | |
filename_idx = idx + n | |
instr_idx = idx + 2 * n | |
prev_output_idx = idx + 3 * n | |
if trig == gen_btn: | |
upload = args[upload_idx] | |
filename = args[filename_idx] | |
instr = args[instr_idx] or "" | |
doc_type = tab_id.replace('-', ' ').title().replace(' ', '') | |
doc_type = next((k for k in document_types if k.lower().replace(' ', '') == tab_id.replace('-', '')), tab_id.title()) | |
if upload and filename: | |
doc = process_document(upload, filename) | |
else: | |
doc = "" | |
if doc or tab_id == "virtual-board": | |
content, df = generate_content(doc, doc_type) | |
if not df.empty: | |
outputs[out_idx] = dash_table.DataTable( | |
data=df.to_dict('records'), | |
columns=[{'name': i, 'id': i} for i in df.columns], | |
style_table={'overflowX': 'auto'}, | |
style_cell={'textAlign': 'left', 'padding': '5px'}, | |
style_header={'fontWeight': 'bold'} | |
) | |
else: | |
outputs[out_idx] = dcc.Markdown(content) | |
else: | |
outputs[out_idx] = "Please upload a document to begin." | |
elif trig == dl_btn: | |
prev_output = args[prev_output_idx] | |
if prev_output and hasattr(prev_output, 'props') and 'data' in prev_output.props: | |
df = pd.DataFrame(prev_output.props['data']) | |
buffer = BytesIO() | |
df.to_csv(buffer, index=False) | |
outputs[dl_idx] = dcc.send_bytes(buffer.getvalue(), f"{tab_id}_report.csv") | |
elif prev_output: | |
buffer = BytesIO(prev_output.encode("utf-8") if isinstance(prev_output, str) else b"") | |
outputs[dl_idx] = dcc.send_bytes(buffer.getvalue(), f"{tab_id}_report.txt") | |
else: | |
outputs[dl_idx] = None | |
return outputs | |
if __name__ == '__main__': | |
print("Starting the Dash application...") | |
threading.Thread(target=lambda: app.run(debug=True, host='0.0.0.0', port=7860, threaded=True)).start() | |
print("Dash application has finished running.") |