IAMTFRMZA commited on
Commit
28a9534
Β·
verified Β·
1 Parent(s): c95810e

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +115 -113
app.py CHANGED
@@ -52,132 +52,134 @@ client = OpenAI(api_key=OPENAI_API_KEY)
52
  tab1, tab2, tab3 = st.tabs(["πŸ“‘ Contract", "πŸ“ Technical", "πŸ’¬ Chat Assistant"])
53
 
54
  # ------------------ Contract Tab ------------------
 
55
  with tab1:
56
  ASSISTANT_ID = "asst_KsQRedoJUnEeStzfox1o06lO"
57
 
58
- if "messages" not in st.session_state:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  st.session_state.messages = []
60
- if "thread_id" not in st.session_state:
61
  st.session_state.thread_id = None
62
- if "image_url" not in st.session_state:
63
  st.session_state.image_url = None
64
- if "image_updated" not in st.session_state:
65
  st.session_state.image_updated = False
66
- if "pending_prompt" not in st.session_state:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  st.session_state.pending_prompt = None
68
 
69
- with st.sidebar:
70
- st.header("ℹ️ Contract Tools")
71
- if st.button("🧹 Clear Chat"):
72
- st.session_state.messages = []
73
- st.session_state.thread_id = None
74
- st.session_state.image_url = None
75
- st.session_state.image_updated = False
76
- st.session_state.pending_prompt = None
77
- st.rerun()
78
 
79
- show_image = st.toggle("πŸ“‘ Show Page Image", value=True)
80
- keyword = st.text_input("Search by Keyword", placeholder="e.g. defects, WHS, delay")
81
- if st.button("πŸ”Ž Search Keyword") and keyword:
82
- st.session_state.pending_prompt = f"Find clauses or references related to: {keyword}"
83
-
84
- section_options = [
85
- "Select a section...",
86
- "1. Formal Instrument of Contract",
87
- "2. Offer and Acceptance",
88
- "3. Key Personnel",
89
- "4. Contract Pricing",
90
- "5. Specifications",
91
- "6. WHS Policies",
92
- "7. Penalties and Delays",
93
- "8. Dispute Resolution",
94
- "9. Principal Obligations"
95
- ]
96
- section = st.selectbox("πŸ“„ Jump to Section", section_options)
97
- if section != section_options[0]:
98
- st.session_state.pending_prompt = f"Summarize or list key points from section: {section}"
99
-
100
- actions = [
101
- "Select an action...",
102
- "List all contractual obligations",
103
- "Summarize payment terms",
104
- "List WHS responsibilities",
105
- "Find delay-related penalties",
106
- "Extract dispute resolution steps"
107
- ]
108
- action = st.selectbox("βš™οΈ Common Queries", actions)
109
- if action != actions[0]:
110
- st.session_state.pending_prompt = action
111
-
112
- chat_col, image_col = st.columns([2, 1])
113
- with chat_col:
114
- st.markdown("### 🧠 Ask a Document-Specific Question")
115
- user_input = st.chat_input("Example: What is the defects liability period?")
116
- if user_input:
117
- st.session_state.messages.append({"role": "user", "content": user_input})
118
- elif st.session_state.pending_prompt:
119
- st.session_state.messages.append({"role": "user", "content": st.session_state.pending_prompt})
120
- st.session_state.pending_prompt = None
121
-
122
- if st.session_state.messages and st.session_state.messages[-1]["role"] == "user":
123
- try:
124
- if st.session_state.thread_id is None:
125
- thread = client.beta.threads.create()
126
- st.session_state.thread_id = thread.id
127
-
128
- client.beta.threads.messages.create(
129
- thread_id=st.session_state.thread_id,
130
- role="user",
131
- content=st.session_state.messages[-1]["content"]
132
- )
133
-
134
- run = client.beta.threads.runs.create(
135
- thread_id=st.session_state.thread_id,
136
- assistant_id=ASSISTANT_ID
137
- )
138
-
139
- with st.spinner("πŸ€– Thinking..."):
140
- while True:
141
- status = client.beta.threads.runs.retrieve(thread_id=st.session_state.thread_id, run_id=run.id)
142
- if status.status in ("completed", "failed", "cancelled"):
143
- break
144
- time.sleep(1)
145
-
146
- if status.status == "completed":
147
- messages = client.beta.threads.messages.list(thread_id=st.session_state.thread_id)
148
- for m in reversed(messages.data):
149
- if m.role == "assistant":
150
- reply = m.content[0].text.value
151
- st.session_state.messages.append({"role": "assistant", "content": reply})
152
- match = re.search(r'Document Reference:\s*(.*?),\s*Page\s*(\d+)', reply)
153
- if match:
154
- doc, page = match.group(1).strip(), int(match.group(2))
155
- folder = quote(doc)
156
- img_url = f"https://raw.githubusercontent.com/AndrewLORTech/c2ozschlaegerforrestdale/main/{folder}/{folder}_page_{page:04d}.png"
157
- st.session_state.image_url = img_url
158
- st.session_state.image_updated = True
159
- break
160
- else:
161
- st.error("❌ Assistant failed.")
162
- st.rerun()
163
- except Exception as e:
164
- st.error(f"❌ Error: {e}")
165
 
166
- for msg in st.session_state.messages:
167
- with st.chat_message(msg["role"]):
168
- st.markdown(msg["content"], unsafe_allow_html=True)
 
169
 
170
- with image_col:
171
- if show_image and st.session_state.image_url:
172
- try:
173
- r = requests.get(st.session_state.image_url)
174
- r.raise_for_status()
175
- img = Image.open(BytesIO(r.content))
176
- st.image(img, caption="πŸ“„ OCR Page Image", use_container_width=True)
177
- except Exception as e:
178
- st.error(f"πŸ–ΌοΈ Image failed: {e}")
179
 
180
- # ------------------ Technical Tab ------------------
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
181
  # ------------------ Technical Tab ------------------
182
  with tab2:
183
  ASSISTANT_ID = "asst_DjvuWBc7tCvMbAhY7n1em4BZ"
 
52
  tab1, tab2, tab3 = st.tabs(["πŸ“‘ Contract", "πŸ“ Technical", "πŸ’¬ Chat Assistant"])
53
 
54
  # ------------------ Contract Tab ------------------
55
+ ------------------ Contract Tab ------------------
56
  with tab1:
57
  ASSISTANT_ID = "asst_KsQRedoJUnEeStzfox1o06lO"
58
 
59
+
60
+
61
+ if "messages" not in st.session_state:
62
+ st.session_state.messages = []
63
+ if "thread_id" not in st.session_state:
64
+ st.session_state.thread_id = None
65
+ if "image_url" not in st.session_state:
66
+ st.session_state.image_url = None
67
+ if "image_updated" not in st.session_state:
68
+ st.session_state.image_updated = False
69
+ if "pending_prompt" not in st.session_state:
70
+ st.session_state.pending_prompt = None
71
+
72
+ with st.sidebar:
73
+ st.header("ℹ️ Contract Tools")
74
+ if st.button("🧹 Clear Chat"):
75
  st.session_state.messages = []
 
76
  st.session_state.thread_id = None
 
77
  st.session_state.image_url = None
 
78
  st.session_state.image_updated = False
79
+ st.session_state.pending_prompt = None
80
+ st.rerun()
81
+
82
+ show_image = st.toggle("πŸ“‘ Show Page Image", value=True)
83
+ keyword = st.text_input("Search by Keyword", placeholder="e.g. defects, WHS, delay")
84
+ if st.button("πŸ”Ž Search Keyword") and keyword:
85
+ st.session_state.pending_prompt = f"Find clauses or references related to: {keyword}"
86
+
87
+ section_options = [
88
+ "Select a section...",
89
+ "1. Formal Instrument of Contract",
90
+ "2. Offer and Acceptance",
91
+ "3. Key Personnel",
92
+ "4. Contract Pricing",
93
+ "5. Specifications",
94
+ "6. WHS Policies",
95
+ "7. Penalties and Delays",
96
+ "8. Dispute Resolution",
97
+ "9. Principal Obligations"
98
+ ]
99
+ section = st.selectbox("πŸ“„ Jump to Section", section_options)
100
+ if section != section_options[0]:
101
+ st.session_state.pending_prompt = f"Summarize or list key points from section: {section}"
102
+
103
+ actions = [
104
+ "Select an action...",
105
+ "List all contractual obligations",
106
+ "Summarize payment terms",
107
+ "List WHS responsibilities",
108
+ "Find delay-related penalties",
109
+ "Extract dispute resolution steps"
110
+ ]
111
+ action = st.selectbox("βš™οΈ Common Queries", actions)
112
+ if action != actions[0]:
113
+ st.session_state.pending_prompt = action
114
+
115
+ chat_col, image_col = st.columns([2, 1])
116
+ with chat_col:
117
+ st.markdown("### 🧠 Ask a Document-Specific Question")
118
+ user_input = st.chat_input("Example: What is the defects liability period?")
119
+ if user_input:
120
+ st.session_state.messages.append({"role": "user", "content": user_input})
121
+ elif st.session_state.pending_prompt:
122
+ st.session_state.messages.append({"role": "user", "content": st.session_state.pending_prompt})
123
  st.session_state.pending_prompt = None
124
 
125
+ if st.session_state.messages and st.session_state.messages[-1]["role"] == "user":
126
+ try:
127
+ if st.session_state.thread_id is None:
128
+ thread = client.beta.threads.create()
129
+ st.session_state.thread_id = thread.id
 
 
 
 
130
 
131
+ client.beta.threads.messages.create(
132
+ thread_id=st.session_state.thread_id,
133
+ role="user",
134
+ content=st.session_state.messages[-1]["content"]
135
+ )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
136
 
137
+ run = client.beta.threads.runs.create(
138
+ thread_id=st.session_state.thread_id,
139
+ assistant_id=ASSISTANT_ID
140
+ )
141
 
142
+ with st.spinner("πŸ€– Thinking..."):
143
+ while True:
144
+ status = client.beta.threads.runs.retrieve(thread_id=st.session_state.thread_id, run_id=run.id)
145
+ if status.status in ("completed", "failed", "cancelled"):
146
+ break
147
+ time.sleep(1)
 
 
 
148
 
149
+ if status.status == "completed":
150
+ messages = client.beta.threads.messages.list(thread_id=st.session_state.thread_id)
151
+ for m in reversed(messages.data):
152
+ if m.role == "assistant":
153
+ reply = m.content[0].text.value
154
+ st.session_state.messages.append({"role": "assistant", "content": reply})
155
+ match = re.search(r'Document Reference:\\s*(.*?),\\s*Page\\s*(\\d+)', reply)
156
+ if match:
157
+ doc, page = match.group(1).strip(), int(match.group(2))
158
+ folder = quote(doc)
159
+ img_url = f"<https://raw.githubusercontent.com/AndrewLORTech/c2ozschlaegerforrestdale/main/{folder}/{folder}_page_{page:04d}.png>"
160
+ st.session_state.image_url = img_url
161
+ st.session_state.image_updated = True
162
+ break
163
+ else:
164
+ st.error("❌ Assistant failed.")
165
+ st.rerun()
166
+ except Exception as e:
167
+ st.error(f"❌ Error: {e}")
168
+
169
+ for msg in st.session_state.messages:
170
+ with st.chat_message(msg["role"]):
171
+ st.markdown(msg["content"], unsafe_allow_html=True)
172
+
173
+ with image_col:
174
+ if show_image and st.session_state.image_url:
175
+ try:
176
+ r = requests.get(st.session_state.image_url)
177
+ r.raise_for_status()
178
+ img = Image.open(BytesIO(r.content))
179
+ st.image(img, caption="πŸ“„ OCR Page Image", use_container_width=True)
180
+ except Exception as e:
181
+ st.error(f"πŸ–ΌοΈ Image failed: {e}")
182
+
183
  # ------------------ Technical Tab ------------------
184
  with tab2:
185
  ASSISTANT_ID = "asst_DjvuWBc7tCvMbAhY7n1em4BZ"