File size: 12,175 Bytes
e60c00e
1167b29
 
27579c4
525d347
1167b29
bd5de4f
1167b29
67360ee
 
1167b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62cf3f2
 
1167b29
 
 
 
 
 
27579c4
1167b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27579c4
 
1167b29
 
27579c4
 
 
 
 
 
1167b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27579c4
1167b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27579c4
 
1167b29
 
27579c4
1167b29
 
27579c4
 
1167b29
 
 
 
 
 
 
 
27579c4
1167b29
 
 
27579c4
1167b29
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27579c4
1167b29
 
3a85524
94cf5e8
 
1167b29
94cf5e8
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
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}

@app.callback(
    Output('main-content', 'children'),
    Input('main-tabs', 'value')
)
def render_tab(tab):
    return tab_cards[tab]

@app.callback(
    [Output(f'{tab_id}-output', 'children') for tab_id in tab_cards] +
    [Output(f"{tab_id}-download", "data") for tab_id in tab_cards],
    [Input(f'{tab_id}-btn', 'n_clicks') for tab_id in tab_cards] +
    [Input(f"{tab_id}-download-btn", "n_clicks") for tab_id in tab_cards],
    [State(f'{tab_id}-upload', 'contents') for tab_id in tab_cards] +
    [State(f'{tab_id}-upload', 'filename') for tab_id in tab_cards] +
    [State(f'{tab_id}-instructions', 'value') for tab_id in tab_cards] +
    [State(f'{tab_id}-output', 'children') for tab_id in tab_cards]
)
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.")