Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,104 +1,93 @@
|
|
1 |
-
import time
|
2 |
import streamlit as st
|
3 |
-
import openai
|
4 |
import os
|
|
|
5 |
import json
|
6 |
-
import
|
7 |
-
import requests
|
8 |
-
from PIL import Image
|
9 |
-
from io import BytesIO
|
10 |
-
from urllib.parse import quote
|
11 |
|
12 |
-
#
|
13 |
-
st.set_page_config(page_title="Forrestdale Technical Drawing Assistant", layout="wide")
|
14 |
-
st.
|
15 |
-
|
16 |
-
<p style='font-size: 1rem;'>Ask about plans, drawings or components</p>
|
17 |
-
""", unsafe_allow_html=True)
|
18 |
|
19 |
-
#
|
20 |
-
OPENAI_API_KEY = os.
|
21 |
-
ASSISTANT_ID = os.
|
|
|
22 |
|
23 |
if not OPENAI_API_KEY or not ASSISTANT_ID:
|
24 |
-
st.error("
|
25 |
st.stop()
|
26 |
|
27 |
-
|
28 |
-
|
29 |
-
|
30 |
-
|
31 |
-
|
32 |
-
match = re.search(r"```json\s*([\s\S]+?)```", response_text.strip())
|
33 |
-
if not match:
|
34 |
-
raise ValueError("No valid JSON block found.")
|
35 |
-
json_str = match.group(1).strip()
|
36 |
-
return json.loads(json_str)
|
37 |
-
except Exception as e:
|
38 |
-
st.error("β οΈ Could not parse assistant response as JSON.")
|
39 |
-
st.stop()
|
40 |
-
|
41 |
-
def display_card(item):
|
42 |
-
st.markdown("""
|
43 |
-
<div style="border: 1px solid #333; border-radius: 12px; padding: 16px; margin: 10px; background-color: #111;">
|
44 |
-
<h3>π {} ({})</h3>
|
45 |
-
<p><b>Discipline:</b> {}</p>
|
46 |
-
<p><b>Summary:</b> {}</p>
|
47 |
-
<div style="display: flex; flex-wrap: wrap; gap: 10px;">
|
48 |
-
""".format(item["drawing_number"], item.get("drawing_type", ""), item["discipline"], item["summary"]), unsafe_allow_html=True)
|
49 |
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
image = Image.open(BytesIO(response.content))
|
55 |
-
st.image(image, caption=os.path.basename(img), width=200)
|
56 |
-
except:
|
57 |
-
st.warning(f"Image failed to load: {img}")
|
58 |
|
59 |
-
|
|
|
|
|
|
|
|
|
60 |
|
61 |
-
|
62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
63 |
|
64 |
-
|
65 |
-
|
66 |
-
|
67 |
-
if "
|
68 |
-
|
69 |
-
|
70 |
|
71 |
-
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
)
|
76 |
-
|
77 |
-
|
78 |
-
|
79 |
-
|
80 |
-
|
81 |
-
|
82 |
-
|
83 |
-
|
84 |
-
|
85 |
-
run_id=run.id
|
86 |
-
)
|
87 |
-
if run_status.status in ["completed", "failed", "cancelled"]:
|
88 |
break
|
89 |
-
|
90 |
-
|
91 |
-
if run_status.status != "completed":
|
92 |
-
st.error(f"β Assistant run failed: {run_status.status}")
|
93 |
-
else:
|
94 |
-
messages = client.beta.threads.messages.list(thread_id=st.session_state.thread_id)
|
95 |
-
for message in reversed(messages.data):
|
96 |
-
if message.role == "assistant":
|
97 |
-
response_text = message.content[0].text.value
|
98 |
-
data = extract_json_from_response(response_text)
|
99 |
-
for item in data:
|
100 |
-
display_card(item)
|
101 |
-
break
|
102 |
|
103 |
-
|
104 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import streamlit as st
|
|
|
2 |
import os
|
3 |
+
import time
|
4 |
import json
|
5 |
+
from openai import OpenAI
|
|
|
|
|
|
|
|
|
6 |
|
7 |
+
# App config
|
8 |
+
st.set_page_config(page_title="ποΈ Forrestdale Technical Drawing Assistant", layout="wide")
|
9 |
+
st.title("ποΈ Forrestdale Technical Drawing Assistant")
|
10 |
+
st.caption("Ask about plans, drawings or components")
|
|
|
|
|
11 |
|
12 |
+
# Load secrets
|
13 |
+
OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
|
14 |
+
ASSISTANT_ID = os.environ.get("ASSISTANT_ID")
|
15 |
+
client = OpenAI(api_key=OPENAI_API_KEY)
|
16 |
|
17 |
if not OPENAI_API_KEY or not ASSISTANT_ID:
|
18 |
+
st.error("Missing secrets: OPENAI_API_KEY or ASSISTANT_ID")
|
19 |
st.stop()
|
20 |
|
21 |
+
# Session setup
|
22 |
+
if "messages" not in st.session_state:
|
23 |
+
st.session_state.messages = []
|
24 |
+
if "thread_id" not in st.session_state:
|
25 |
+
st.session_state.thread_id = None
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
26 |
|
27 |
+
# Prompt input
|
28 |
+
prompt = st.chat_input("Ask something like 'Show me all civil drawings' or 'Where are the switchboards?'")
|
29 |
+
if prompt:
|
30 |
+
st.session_state.messages.append({"role": "user", "content": prompt})
|
|
|
|
|
|
|
|
|
31 |
|
32 |
+
# Chat + assistant processing
|
33 |
+
if st.session_state.messages and st.session_state.messages[-1]["role"] == "user":
|
34 |
+
if st.session_state.thread_id is None:
|
35 |
+
thread = client.beta.threads.create()
|
36 |
+
st.session_state.thread_id = thread.id
|
37 |
|
38 |
+
client.beta.threads.messages.create(
|
39 |
+
thread_id=st.session_state.thread_id,
|
40 |
+
role="user",
|
41 |
+
content=st.session_state.messages[-1]["content"]
|
42 |
+
)
|
43 |
+
run = client.beta.threads.runs.create(
|
44 |
+
thread_id=st.session_state.thread_id,
|
45 |
+
assistant_id=ASSISTANT_ID
|
46 |
+
)
|
47 |
|
48 |
+
with st.spinner("π Querying assistant..."):
|
49 |
+
while True:
|
50 |
+
run_status = client.beta.threads.runs.retrieve(thread_id=st.session_state.thread_id, run_id=run.id)
|
51 |
+
if run_status.status in ("completed", "failed", "cancelled"):
|
52 |
+
break
|
53 |
+
time.sleep(1)
|
54 |
|
55 |
+
if run_status.status != "completed":
|
56 |
+
st.error(f"Assistant failed: {run_status.status}")
|
57 |
+
else:
|
58 |
+
messages = client.beta.threads.messages.list(thread_id=st.session_state.thread_id)
|
59 |
+
for message in reversed(messages.data):
|
60 |
+
if message.role == "assistant":
|
61 |
+
try:
|
62 |
+
raw = message.content[0].text.value.strip()
|
63 |
+
if raw.startswith("```json"):
|
64 |
+
raw = raw.removeprefix("```json").removesuffix("```").strip()
|
65 |
+
data = json.loads(raw)
|
66 |
+
st.session_state.messages.append({"role": "assistant", "content": data})
|
67 |
+
except Exception as e:
|
68 |
+
st.error(f"β οΈ Could not parse assistant response as JSON.\n{e}")
|
|
|
|
|
|
|
69 |
break
|
70 |
+
st.rerun()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
71 |
|
72 |
+
# Card view rendering
|
73 |
+
for msg in st.session_state.messages:
|
74 |
+
if msg["role"] == "assistant":
|
75 |
+
data = msg["content"]
|
76 |
+
if isinstance(data, list) and len(data) > 0:
|
77 |
+
st.markdown("### π Results")
|
78 |
+
cols = st.columns(4)
|
79 |
+
for i, item in enumerate(data):
|
80 |
+
with cols[i % 4]:
|
81 |
+
st.image(item.get("images", [item.get("image")])[0], caption=item["drawing_number"], use_column_width=True)
|
82 |
+
with st.expander("Details"):
|
83 |
+
st.write(f"**Discipline:** {item['discipline']}")
|
84 |
+
st.write(f"**Summary:** {item['summary']}")
|
85 |
+
if "question" in item:
|
86 |
+
st.write(f"**Question:** {item['question']}")
|
87 |
+
for idx, img in enumerate(item.get("images", [])):
|
88 |
+
st.image(img, caption=f"Page {idx+1}", use_column_width=True)
|
89 |
+
else:
|
90 |
+
st.warning("Assistant returned no matching drawings.")
|
91 |
+
elif msg["role"] == "user":
|
92 |
+
with st.chat_message("user"):
|
93 |
+
st.markdown(msg["content"])
|