Spaces:
Paused
Paused
Update app.py via AI Editor
Browse files
app.py
CHANGED
@@ -5,7 +5,7 @@ import dash
|
|
5 |
from dash import dcc, html, Input, Output, State, callback_context
|
6 |
import dash_bootstrap_components as dbc
|
7 |
import pandas as pd
|
8 |
-
import
|
9 |
import logging
|
10 |
from docx import Document
|
11 |
|
@@ -17,14 +17,14 @@ logging.basicConfig(
|
|
17 |
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
|
18 |
server = app.server
|
19 |
|
20 |
-
|
21 |
-
|
22 |
-
|
23 |
-
CLAUDE3_MAX_CONTEXT_TOKENS = 200_000
|
24 |
-
CLAUDE3_MAX_OUTPUT_TOKENS = 64_000
|
25 |
|
26 |
uploaded_documents = {}
|
|
|
27 |
uploaded_proposals = {}
|
|
|
28 |
generated_documents = {}
|
29 |
shredded_documents = {}
|
30 |
shredded_document = None
|
@@ -44,25 +44,43 @@ def decode_document(decoded_bytes):
|
|
44 |
logging.error("Document decode failed for both utf-8 and latin-1: %s", e)
|
45 |
return None
|
46 |
|
47 |
-
def
|
48 |
-
stream_result = []
|
49 |
try:
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
stream=True
|
56 |
-
) as stream:
|
57 |
-
for event in stream:
|
58 |
-
if event.type == "content_block_delta":
|
59 |
-
piece = event.delta.text
|
60 |
-
stream_result.append(piece)
|
61 |
-
logging.debug(f"Streaming piece: {piece}")
|
62 |
-
logging.info("Received response from Anthropic Claude streaming.")
|
63 |
-
return ''.join(stream_result)
|
64 |
except Exception as e:
|
65 |
-
logging.error("
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
66 |
return f"Error during streaming: {e}"
|
67 |
|
68 |
def save_shredded_as_docx(shredded_text, rfp_filename):
|
@@ -90,16 +108,20 @@ def process_document(action, selected_filename=None, chat_input=None, selected_p
|
|
90 |
logging.info(f"Process document called with action: {action}")
|
91 |
|
92 |
doc_content = None
|
|
|
93 |
if action in ["shred", "generate"]:
|
94 |
if selected_filename and selected_filename in uploaded_documents:
|
95 |
doc_content = uploaded_documents[selected_filename]
|
|
|
96 |
elif uploaded_documents:
|
97 |
doc_content = next(iter(uploaded_documents.values()))
|
98 |
selected_filename = next(iter(uploaded_documents.keys()))
|
|
|
99 |
else:
|
100 |
doc_content = None
|
|
|
101 |
elif action == "proposal":
|
102 |
-
pass
|
103 |
|
104 |
if action == 'shred':
|
105 |
if not doc_content:
|
@@ -112,15 +134,14 @@ def process_document(action, selected_filename=None, chat_input=None, selected_p
|
|
112 |
)
|
113 |
if chat_input:
|
114 |
prompt += f"User additional instructions: {chat_input}\n"
|
115 |
-
prompt += f"\nFile Name: {selected_filename}\n\n
|
116 |
-
|
117 |
result_holder = {"text": None, "docx_bytes": None, "docx_name": None}
|
118 |
def thread_shred():
|
119 |
global shredded_document
|
120 |
shredded_document = ""
|
121 |
try:
|
122 |
-
logging.info("Starting streaming shredding operation with
|
123 |
-
result =
|
124 |
shredded_document = result
|
125 |
logging.info("Document shredded successfully.")
|
126 |
docx_bytes = save_shredded_as_docx(result, selected_filename)
|
@@ -156,8 +177,8 @@ def process_document(action, selected_filename=None, chat_input=None, selected_p
|
|
156 |
global generated_response
|
157 |
generated_response = ""
|
158 |
try:
|
159 |
-
logging.info("Starting streaming generation operation with
|
160 |
-
result =
|
161 |
generated_response = result
|
162 |
logging.info("Proposal response generated successfully.")
|
163 |
docx_bytes = save_proposal_as_docx(result, selected_filename)
|
@@ -181,6 +202,8 @@ def process_document(action, selected_filename=None, chat_input=None, selected_p
|
|
181 |
generated_doc_content = None
|
182 |
rfp_filename = selected_filename
|
183 |
generated_docname = selected_generated
|
|
|
|
|
184 |
if not (selected_filename and selected_filename in uploaded_documents):
|
185 |
logging.warning("No RFP/SOW/PWS/RFI document selected for proposal action.")
|
186 |
return "No RFP/SOW/PWS/RFI document selected.", None, None
|
@@ -211,15 +234,22 @@ def process_document(action, selected_filename=None, chat_input=None, selected_p
|
|
211 |
)
|
212 |
if chat_input:
|
213 |
prompt += f"User additional instructions: {chat_input}\n"
|
214 |
-
prompt += f"\n---\nRFP/SOW/PWS/RFI ({rfp_filename}):\n
|
215 |
prompt += f"\n---\nGenerated Document ({generated_docname}):\n{generated_doc_content}\n"
|
216 |
-
logging.info(f"Sending proposal prompt to
|
217 |
result_holder = {"text": None, "docx_bytes": None, "docx_name": None}
|
218 |
def thread_proposal():
|
219 |
try:
|
220 |
-
logging.info("Connecting to
|
221 |
-
|
222 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
223 |
docx_bytes = save_proposal_as_docx(result, rfp_filename)
|
224 |
generated_docx_name = f"{os.path.splitext(rfp_filename)[0]}_{os.path.splitext(generated_docname)[0]}_proposal.docx"
|
225 |
result_holder["text"] = result
|
@@ -475,8 +505,13 @@ def master_callback(
|
|
475 |
content_type, content_string = rfp_content.split(',')
|
476 |
decoded = base64.b64decode(content_string)
|
477 |
text = decode_document(decoded)
|
|
|
|
|
|
|
478 |
if text is not None:
|
479 |
uploaded_documents[rfp_filename] = text
|
|
|
|
|
480 |
logging.info(f"Document uploaded: {rfp_filename}")
|
481 |
else:
|
482 |
logging.error(f"Failed to decode uploaded document: {rfp_filename}")
|
@@ -486,8 +521,13 @@ def master_callback(
|
|
486 |
content_type, content_string = proposal_content.split(',')
|
487 |
decoded = base64.b64decode(content_string)
|
488 |
text = decode_document(decoded)
|
|
|
|
|
|
|
489 |
if text is not None:
|
490 |
uploaded_proposals[proposal_filename] = text
|
|
|
|
|
491 |
logging.info(f"Proposal uploaded: {proposal_filename}")
|
492 |
else:
|
493 |
logging.error(f"Failed to decode uploaded proposal: {proposal_filename}")
|
@@ -500,6 +540,8 @@ def master_callback(
|
|
500 |
del_filename = btn_id['index']
|
501 |
if del_filename in uploaded_documents:
|
502 |
del uploaded_documents[del_filename]
|
|
|
|
|
503 |
logging.info(f"Document deleted: {del_filename}")
|
504 |
if selected_doc == del_filename:
|
505 |
selected_doc = next(iter(uploaded_documents), None)
|
@@ -513,6 +555,8 @@ def master_callback(
|
|
513 |
del_filename = btn_id['index']
|
514 |
if del_filename in uploaded_proposals:
|
515 |
del uploaded_proposals[del_filename]
|
|
|
|
|
516 |
logging.info(f"Proposal deleted: {del_filename}")
|
517 |
if selected_proposal == del_filename:
|
518 |
selected_proposal = next(iter(uploaded_proposals), None)
|
|
|
5 |
from dash import dcc, html, Input, Output, State, callback_context
|
6 |
import dash_bootstrap_components as dbc
|
7 |
import pandas as pd
|
8 |
+
import openai
|
9 |
import logging
|
10 |
from docx import Document
|
11 |
|
|
|
17 |
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])
|
18 |
server = app.server
|
19 |
|
20 |
+
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY", "")
|
21 |
+
openai.api_key = OPENAI_API_KEY
|
22 |
+
OPENAI_MODEL = "gpt-4.1"
|
|
|
|
|
23 |
|
24 |
uploaded_documents = {}
|
25 |
+
uploaded_documents_fileid = {}
|
26 |
uploaded_proposals = {}
|
27 |
+
uploaded_proposals_fileid = {}
|
28 |
generated_documents = {}
|
29 |
shredded_documents = {}
|
30 |
shredded_document = None
|
|
|
44 |
logging.error("Document decode failed for both utf-8 and latin-1: %s", e)
|
45 |
return None
|
46 |
|
47 |
+
def upload_to_openai_file(decoded_bytes, filename):
|
|
|
48 |
try:
|
49 |
+
memfile = io.BytesIO(decoded_bytes)
|
50 |
+
memfile.seek(0)
|
51 |
+
resp = openai.files.create(file=memfile, purpose="assistants", file_name=filename)
|
52 |
+
logging.info(f"File uploaded to OpenAI: {filename}, file_id: {resp.id}")
|
53 |
+
return resp.id
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
54 |
except Exception as e:
|
55 |
+
logging.error(f"Failed uploading file to OpenAI API: {e}")
|
56 |
+
return None
|
57 |
+
|
58 |
+
def openai_stream_generate(prompt, file_id=None):
|
59 |
+
result_text = []
|
60 |
+
try:
|
61 |
+
logging.info("Connecting to OpenAI gpt-4.1 for streaming completion...")
|
62 |
+
messages = [{"role": "user", "content": prompt}]
|
63 |
+
extra_kwargs = {}
|
64 |
+
if file_id:
|
65 |
+
extra_kwargs["files"] = [file_id]
|
66 |
+
logging.info(f"Passing file_id to OpenAI ChatCompletion: {file_id}")
|
67 |
+
stream = openai.chat.completions.create(
|
68 |
+
model=OPENAI_MODEL,
|
69 |
+
messages=messages,
|
70 |
+
max_tokens=64000,
|
71 |
+
temperature=0.2,
|
72 |
+
stream=True,
|
73 |
+
**extra_kwargs
|
74 |
+
)
|
75 |
+
for chunk in stream:
|
76 |
+
if hasattr(chunk, 'choices') and chunk.choices and hasattr(chunk.choices[0].delta, 'content'):
|
77 |
+
piece = chunk.choices[0].delta.content
|
78 |
+
if piece:
|
79 |
+
result_text.append(piece)
|
80 |
+
logging.info("Received response from OpenAI streaming.")
|
81 |
+
return ''.join(result_text)
|
82 |
+
except Exception as e:
|
83 |
+
logging.error("Error during OpenAI streaming request: %s", e)
|
84 |
return f"Error during streaming: {e}"
|
85 |
|
86 |
def save_shredded_as_docx(shredded_text, rfp_filename):
|
|
|
108 |
logging.info(f"Process document called with action: {action}")
|
109 |
|
110 |
doc_content = None
|
111 |
+
doc_fileid = None
|
112 |
if action in ["shred", "generate"]:
|
113 |
if selected_filename and selected_filename in uploaded_documents:
|
114 |
doc_content = uploaded_documents[selected_filename]
|
115 |
+
doc_fileid = uploaded_documents_fileid.get(selected_filename)
|
116 |
elif uploaded_documents:
|
117 |
doc_content = next(iter(uploaded_documents.values()))
|
118 |
selected_filename = next(iter(uploaded_documents.keys()))
|
119 |
+
doc_fileid = uploaded_documents_fileid.get(selected_filename)
|
120 |
else:
|
121 |
doc_content = None
|
122 |
+
doc_fileid = None
|
123 |
elif action == "proposal":
|
124 |
+
pass
|
125 |
|
126 |
if action == 'shred':
|
127 |
if not doc_content:
|
|
|
134 |
)
|
135 |
if chat_input:
|
136 |
prompt += f"User additional instructions: {chat_input}\n"
|
137 |
+
prompt += f"\nFile Name: {selected_filename}\n\n"
|
|
|
138 |
result_holder = {"text": None, "docx_bytes": None, "docx_name": None}
|
139 |
def thread_shred():
|
140 |
global shredded_document
|
141 |
shredded_document = ""
|
142 |
try:
|
143 |
+
logging.info("Starting streaming shredding operation with OpenAI.")
|
144 |
+
result = openai_stream_generate(prompt, file_id=doc_fileid)
|
145 |
shredded_document = result
|
146 |
logging.info("Document shredded successfully.")
|
147 |
docx_bytes = save_shredded_as_docx(result, selected_filename)
|
|
|
177 |
global generated_response
|
178 |
generated_response = ""
|
179 |
try:
|
180 |
+
logging.info("Starting streaming generation operation with OpenAI.")
|
181 |
+
result = openai_stream_generate(prompt, file_id=doc_fileid)
|
182 |
generated_response = result
|
183 |
logging.info("Proposal response generated successfully.")
|
184 |
docx_bytes = save_proposal_as_docx(result, selected_filename)
|
|
|
202 |
generated_doc_content = None
|
203 |
rfp_filename = selected_filename
|
204 |
generated_docname = selected_generated
|
205 |
+
rfp_fileid = uploaded_documents_fileid.get(selected_filename)
|
206 |
+
gen_fileid = None
|
207 |
if not (selected_filename and selected_filename in uploaded_documents):
|
208 |
logging.warning("No RFP/SOW/PWS/RFI document selected for proposal action.")
|
209 |
return "No RFP/SOW/PWS/RFI document selected.", None, None
|
|
|
234 |
)
|
235 |
if chat_input:
|
236 |
prompt += f"User additional instructions: {chat_input}\n"
|
237 |
+
prompt += f"\n---\nRFP/SOW/PWS/RFI ({rfp_filename}):\n"
|
238 |
prompt += f"\n---\nGenerated Document ({generated_docname}):\n{generated_doc_content}\n"
|
239 |
+
logging.info(f"Sending proposal prompt to OpenAI. RFP: {rfp_filename}, Generated Doc: {generated_docname}")
|
240 |
result_holder = {"text": None, "docx_bytes": None, "docx_name": None}
|
241 |
def thread_proposal():
|
242 |
try:
|
243 |
+
logging.info("Connecting to OpenAI gpt-4.1 for proposal streaming...")
|
244 |
+
# Attach both files if available and not None
|
245 |
+
pass_files = []
|
246 |
+
if rfp_fileid:
|
247 |
+
pass_files.append(rfp_fileid)
|
248 |
+
if gen_fileid:
|
249 |
+
pass_files.append(gen_fileid)
|
250 |
+
file_arg = pass_files if pass_files else None
|
251 |
+
result = openai_stream_generate(prompt, file_id=file_arg[0] if file_arg else None)
|
252 |
+
logging.info("Received proposal results from OpenAI.")
|
253 |
docx_bytes = save_proposal_as_docx(result, rfp_filename)
|
254 |
generated_docx_name = f"{os.path.splitext(rfp_filename)[0]}_{os.path.splitext(generated_docname)[0]}_proposal.docx"
|
255 |
result_holder["text"] = result
|
|
|
505 |
content_type, content_string = rfp_content.split(',')
|
506 |
decoded = base64.b64decode(content_string)
|
507 |
text = decode_document(decoded)
|
508 |
+
fileid = None
|
509 |
+
if rfp_filename.lower().endswith(('.pdf', '.docx', '.xlsx', '.xls')):
|
510 |
+
fileid = upload_to_openai_file(decoded, rfp_filename)
|
511 |
if text is not None:
|
512 |
uploaded_documents[rfp_filename] = text
|
513 |
+
if fileid:
|
514 |
+
uploaded_documents_fileid[rfp_filename] = fileid
|
515 |
logging.info(f"Document uploaded: {rfp_filename}")
|
516 |
else:
|
517 |
logging.error(f"Failed to decode uploaded document: {rfp_filename}")
|
|
|
521 |
content_type, content_string = proposal_content.split(',')
|
522 |
decoded = base64.b64decode(content_string)
|
523 |
text = decode_document(decoded)
|
524 |
+
fileid = None
|
525 |
+
if proposal_filename.lower().endswith(('.pdf', '.docx', '.xlsx', '.xls')):
|
526 |
+
fileid = upload_to_openai_file(decoded, proposal_filename)
|
527 |
if text is not None:
|
528 |
uploaded_proposals[proposal_filename] = text
|
529 |
+
if fileid:
|
530 |
+
uploaded_proposals_fileid[proposal_filename] = fileid
|
531 |
logging.info(f"Proposal uploaded: {proposal_filename}")
|
532 |
else:
|
533 |
logging.error(f"Failed to decode uploaded proposal: {proposal_filename}")
|
|
|
540 |
del_filename = btn_id['index']
|
541 |
if del_filename in uploaded_documents:
|
542 |
del uploaded_documents[del_filename]
|
543 |
+
if del_filename in uploaded_documents_fileid:
|
544 |
+
del uploaded_documents_fileid[del_filename]
|
545 |
logging.info(f"Document deleted: {del_filename}")
|
546 |
if selected_doc == del_filename:
|
547 |
selected_doc = next(iter(uploaded_documents), None)
|
|
|
555 |
del_filename = btn_id['index']
|
556 |
if del_filename in uploaded_proposals:
|
557 |
del uploaded_proposals[del_filename]
|
558 |
+
if del_filename in uploaded_proposals_fileid:
|
559 |
+
del uploaded_proposals_fileid[del_filename]
|
560 |
logging.info(f"Proposal deleted: {del_filename}")
|
561 |
if selected_proposal == del_filename:
|
562 |
selected_proposal = next(iter(uploaded_proposals), None)
|