IAMTFRMZA commited on
Commit
af951b6
Β·
verified Β·
1 Parent(s): 1ba534e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +43 -66
app.py CHANGED
@@ -9,8 +9,8 @@ from openai import OpenAI
9
 
10
  # ------------------ App Configuration ------------------
11
  st.set_page_config(page_title="Schlaeger Forrestdale DocAIA", layout="wide")
12
- st.title("πŸ“„ Document AI Assistant")
13
- st.caption("Chat with an AI Assistant on your construction documents")
14
 
15
  # ------------------ Load API Key and Assistant ID ------------------
16
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
@@ -32,113 +32,90 @@ if "image_url" not in st.session_state:
32
  if "image_updated" not in st.session_state:
33
  st.session_state.image_updated = False
34
 
35
- # ------------------ Sidebar Controls ------------------
36
- st.sidebar.header("πŸ”§ Settings")
37
- if st.sidebar.button("πŸ”„ Clear Chat"):
38
  st.session_state.messages = []
39
  st.session_state.thread_id = None
40
  st.session_state.image_url = None
41
  st.session_state.image_updated = False
42
  st.rerun()
43
 
44
- show_image = st.sidebar.checkbox("πŸ“– Show Document Image", value=True)
45
 
46
- # ------------------ Layout: Image + Chat ------------------
47
- col1, col2 = st.columns([1, 2])
48
 
49
- # ------------------ Left Panel: Image ------------------
50
- with col1:
51
  if show_image and st.session_state.image_url:
52
- with st.spinner("πŸ–ΌοΈ Loading image preview..."):
53
  try:
54
  response = requests.get(st.session_state.image_url)
55
  response.raise_for_status()
56
  img = Image.open(BytesIO(response.content))
57
- st.image(img, caption="πŸ“‘ Extracted Page", use_container_width=True)
58
  st.session_state.image_updated = False
59
  except Exception as e:
60
- st.warning(f"⚠️ Failed to load image from URL:\n{st.session_state.image_url}\n\nError: {e}")
61
-
62
- # ------------------ Right Panel: Chat ------------------
63
- with col2:
64
- prompt = st.chat_input("Type your question about the document or choose from FAQs below...")
65
-
66
- # Display chat history in a cleaner bubble layout
67
- paired_messages = []
68
- buffer = []
 
 
 
 
 
 
 
 
 
 
 
 
69
  for msg in st.session_state.messages:
70
- buffer.append(msg)
71
- if msg["role"] == "assistant" and len(buffer) == 2:
72
- paired_messages.append(buffer.copy())
73
- buffer.clear()
74
- if buffer:
75
- paired_messages.append(buffer.copy())
76
-
77
- for pair in reversed(paired_messages):
78
- for msg in pair:
79
- with st.chat_message(msg["role"]):
80
- st.markdown(f"{msg['content']}", unsafe_allow_html=True)
81
 
82
  if prompt:
83
  st.session_state.messages.append({"role": "user", "content": prompt})
84
-
85
  try:
86
  if st.session_state.thread_id is None:
87
  thread = client.beta.threads.create()
88
  st.session_state.thread_id = thread.id
89
 
90
- client.beta.threads.messages.create(
91
- thread_id=st.session_state.thread_id,
92
- role="user",
93
- content=prompt
94
- )
95
 
96
- run = client.beta.threads.runs.create(
97
- thread_id=st.session_state.thread_id,
98
- assistant_id=ASSISTANT_ID
99
- )
100
 
101
- with st.spinner("πŸ€– Assistant is thinking..."):
102
  while True:
103
- run_status = client.beta.threads.runs.retrieve(
104
- thread_id=st.session_state.thread_id,
105
- run_id=run.id
106
- )
107
  if run_status.status == "completed":
108
  break
109
  time.sleep(1)
110
 
111
  messages = client.beta.threads.messages.list(thread_id=st.session_state.thread_id)
112
- assistant_message = None
113
  for message in reversed(messages.data):
114
  if message.role == "assistant":
115
  assistant_message = message.content[0].text.value
 
116
  break
117
 
118
- st.session_state.messages.append({"role": "assistant", "content": assistant_message})
119
-
120
  match = re.search(r'Document Reference:\s+(.+?),\s+Page\s+(\d+)', assistant_message)
121
  if match:
122
  doc_name = match.group(1).strip()
123
  page = int(match.group(2))
124
  page_str = f"{page:04d}"
125
- corrected_url = (
126
- f"https://raw.githubusercontent.com/AndrewLORTech/c2ozschlaegerforrestdale/main/"
127
- f"{doc_name}/{doc_name}_page_{page_str}.png"
128
- )
129
- st.session_state.image_url = corrected_url
130
  st.session_state.image_updated = True
131
 
132
  st.rerun()
133
-
134
  except Exception as e:
135
- st.error(f"❌ Error: {str(e)}")
136
-
137
- # ------------------ Suggested FAQs Section ------------------
138
- st.markdown("""
139
- <hr>
140
- <b>🧠 Suggested FAQs:</b>
141
- - What are the mechanical services on page 3?
142
- - Summarize the demolition schedule.
143
- - List the safety compliance steps.
144
- """)
 
9
 
10
  # ------------------ App Configuration ------------------
11
  st.set_page_config(page_title="Schlaeger Forrestdale DocAIA", layout="wide")
12
+ st.title("πŸ“„ Schlaeger Forrestdale Document Assistant")
13
+ st.caption("Chat with construction documents using OCR-based AI")
14
 
15
  # ------------------ Load API Key and Assistant ID ------------------
16
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
 
32
  if "image_updated" not in st.session_state:
33
  st.session_state.image_updated = False
34
 
35
+ # ------------------ Sidebar ------------------
36
+ st.sidebar.header("βš™οΈ Settings")
37
+ if st.sidebar.button("🧹 Clear Chat"):
38
  st.session_state.messages = []
39
  st.session_state.thread_id = None
40
  st.session_state.image_url = None
41
  st.session_state.image_updated = False
42
  st.rerun()
43
 
44
+ show_image = st.sidebar.toggle("πŸ“‘ Show Page Image", value=True)
45
 
46
+ # ------------------ Layout ------------------
47
+ image_col, chat_col = st.columns([1, 2])
48
 
49
+ # ------------------ Image Viewer ------------------
50
+ with image_col:
51
  if show_image and st.session_state.image_url:
52
+ with st.spinner("Loading document preview..."):
53
  try:
54
  response = requests.get(st.session_state.image_url)
55
  response.raise_for_status()
56
  img = Image.open(BytesIO(response.content))
57
+ st.image(img, caption="πŸ“„ OCR Page Image", use_container_width=True)
58
  st.session_state.image_updated = False
59
  except Exception as e:
60
+ st.error(f"❗ Failed to load image: {e}")
61
+
62
+ # ------------------ Chat Interface ------------------
63
+ with chat_col:
64
+ st.markdown("### 🧠 Ask a Question or Choose Below")
65
+ prompt = st.chat_input("What would you like to ask about the construction documents?")
66
+
67
+ # Quick Action Buttons
68
+ st.markdown("#### ⚑ Quick Prompts")
69
+ quick_cols = st.columns(3)
70
+ with quick_cols[0]:
71
+ if st.button("πŸ” Summary Mode"):
72
+ prompt = "Summarize this section."
73
+ with quick_cols[1]:
74
+ if st.button("πŸ“˜ FAQ Mode"):
75
+ prompt = "Generate FAQs from this section."
76
+ with quick_cols[2]:
77
+ if st.button("🧾 Compliance Info"):
78
+ prompt = "What are the safety and compliance measures?"
79
+
80
+ # Display Message History
81
  for msg in st.session_state.messages:
82
+ with st.chat_message(msg["role"]):
83
+ st.markdown(msg["content"])
 
 
 
 
 
 
 
 
 
84
 
85
  if prompt:
86
  st.session_state.messages.append({"role": "user", "content": prompt})
 
87
  try:
88
  if st.session_state.thread_id is None:
89
  thread = client.beta.threads.create()
90
  st.session_state.thread_id = thread.id
91
 
92
+ client.beta.threads.messages.create(thread_id=st.session_state.thread_id, role="user", content=prompt)
 
 
 
 
93
 
94
+ run = client.beta.threads.runs.create(thread_id=st.session_state.thread_id, assistant_id=ASSISTANT_ID)
 
 
 
95
 
96
+ with st.spinner("πŸ€– Processing your query..."):
97
  while True:
98
+ run_status = client.beta.threads.runs.retrieve(thread_id=st.session_state.thread_id, run_id=run.id)
 
 
 
99
  if run_status.status == "completed":
100
  break
101
  time.sleep(1)
102
 
103
  messages = client.beta.threads.messages.list(thread_id=st.session_state.thread_id)
 
104
  for message in reversed(messages.data):
105
  if message.role == "assistant":
106
  assistant_message = message.content[0].text.value
107
+ st.session_state.messages.append({"role": "assistant", "content": assistant_message})
108
  break
109
 
 
 
110
  match = re.search(r'Document Reference:\s+(.+?),\s+Page\s+(\d+)', assistant_message)
111
  if match:
112
  doc_name = match.group(1).strip()
113
  page = int(match.group(2))
114
  page_str = f"{page:04d}"
115
+ image_url = f"https://raw.githubusercontent.com/AndrewLORTech/c2ozschlaegerforrestdale/main/{doc_name}/{doc_name}_page_{page_str}.png"
116
+ st.session_state.image_url = image_url
 
 
 
117
  st.session_state.image_updated = True
118
 
119
  st.rerun()
 
120
  except Exception as e:
121
+ st.error(f"❌ Error: {e}")