IAMTFRMZA commited on
Commit
3e6c499
Β·
verified Β·
1 Parent(s): b3afc0f

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +19 -24
app.py CHANGED
@@ -7,15 +7,14 @@ from openai import OpenAI
7
  # ------------------ App Configuration ------------------
8
  st.set_page_config(page_title="Document AI Assistant", layout="wide")
9
  st.title("πŸ“„ Document AI Assistant")
10
- st.caption("Chat with an AI Assistant on your medical/pathology documents")
11
 
12
- # ------------------ Load API Key and Assistant ID from Hugging Face Secrets ------------------
13
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
14
  ASSISTANT_ID = os.environ.get("ASSISTANT_ID")
15
 
16
- # ------------------ Error Handling for Missing Secrets ------------------
17
  if not OPENAI_API_KEY or not ASSISTANT_ID:
18
- st.error("Missing secrets. Please ensure both OPENAI_API_KEY and ASSISTANT_ID are set in your Hugging Face Space secrets.")
19
  st.stop()
20
 
21
  client = OpenAI(api_key=OPENAI_API_KEY)
@@ -41,21 +40,20 @@ if st.sidebar.button("πŸ”„ Clear Chat"):
41
 
42
  show_image = st.sidebar.checkbox("πŸ“– Show Document Image", value=True)
43
 
44
- # ------------------ Layout: Image (Left) and Chat (Right) ------------------
45
  col1, col2 = st.columns([1, 2])
46
 
47
- # ------------------ Left Panel: Document Image ------------------
48
  with col1:
49
  if show_image and st.session_state.image_url:
50
  st.image(st.session_state.image_url, caption="πŸ“‘ Extracted Page", use_container_width=True)
51
  st.session_state.image_updated = False
52
 
53
- # ------------------ Right Panel: Chat Interface ------------------
54
  with col2:
55
- # -- Chat Input (Always at the Top)
56
  prompt = st.chat_input("Type your question about the document...")
57
 
58
- # -- Pair messages (user + assistant) for display
59
  paired_messages = []
60
  buffer = []
61
  for msg in st.session_state.messages:
@@ -66,37 +64,34 @@ with col2:
66
  if buffer:
67
  paired_messages.append(buffer.copy())
68
 
69
- # -- Display chat history (latest first, older scroll down)
70
- with st.container():
71
- for pair in reversed(paired_messages):
72
- for msg in pair:
73
- with st.chat_message(msg["role"]):
74
- st.write(msg["content"])
75
 
76
- # -- Process new prompt if entered
77
  if prompt:
78
  st.session_state.messages.append({"role": "user", "content": prompt})
79
 
80
  try:
81
- # Initialize thread if not already done
82
  if st.session_state.thread_id is None:
83
  thread = client.beta.threads.create()
84
  st.session_state.thread_id = thread.id
85
 
86
- # Send user message to assistant
87
  client.beta.threads.messages.create(
88
  thread_id=st.session_state.thread_id,
89
  role="user",
90
  content=prompt
91
  )
92
 
93
- # Trigger assistant run
94
  run = client.beta.threads.runs.create(
95
  thread_id=st.session_state.thread_id,
96
  assistant_id=ASSISTANT_ID
97
  )
98
 
99
- # Wait for assistant to respond
100
  with st.spinner("Assistant is thinking..."):
101
  while True:
102
  run_status = client.beta.threads.runs.retrieve(
@@ -107,7 +102,7 @@ with col2:
107
  break
108
  time.sleep(1)
109
 
110
- # Retrieve latest assistant message
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):
@@ -117,16 +112,16 @@ with col2:
117
 
118
  st.session_state.messages.append({"role": "assistant", "content": assistant_message})
119
 
120
- # -- Extract GitHub-hosted image URL if present
121
  image_match = re.search(
122
- r'https://raw\.githubusercontent\.com/AndrewLORTech/surgical-pathology-manual/main/[\w\-/]*\.png',
123
  assistant_message
124
  )
125
  if image_match:
126
  st.session_state.image_url = image_match.group(0)
127
  st.session_state.image_updated = True
128
 
129
- st.rerun() # Rerun to show updated image + message at top
130
 
131
  except Exception as e:
132
  st.error(f"❌ Error: {str(e)}")
 
7
  # ------------------ App Configuration ------------------
8
  st.set_page_config(page_title="Document AI Assistant", layout="wide")
9
  st.title("πŸ“„ Document AI Assistant")
10
+ st.caption("Chat with an AI Assistant on your medical/pathology or construction documents")
11
 
12
+ # ------------------ Load API Key and Assistant ID ------------------
13
  OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
14
  ASSISTANT_ID = os.environ.get("ASSISTANT_ID")
15
 
 
16
  if not OPENAI_API_KEY or not ASSISTANT_ID:
17
+ st.error("❌ Missing secrets. Please set both OPENAI_API_KEY and ASSISTANT_ID in Hugging Face Space secrets.")
18
  st.stop()
19
 
20
  client = OpenAI(api_key=OPENAI_API_KEY)
 
40
 
41
  show_image = st.sidebar.checkbox("πŸ“– Show Document Image", value=True)
42
 
43
+ # ------------------ Layout: Image + Chat ------------------
44
  col1, col2 = st.columns([1, 2])
45
 
46
+ # ------------------ Left Panel: Image ------------------
47
  with col1:
48
  if show_image and st.session_state.image_url:
49
  st.image(st.session_state.image_url, caption="πŸ“‘ Extracted Page", use_container_width=True)
50
  st.session_state.image_updated = False
51
 
52
+ # ------------------ Right Panel: Chat ------------------
53
  with col2:
 
54
  prompt = st.chat_input("Type your question about the document...")
55
 
56
+ # Display chat history
57
  paired_messages = []
58
  buffer = []
59
  for msg in st.session_state.messages:
 
64
  if buffer:
65
  paired_messages.append(buffer.copy())
66
 
67
+ for pair in reversed(paired_messages):
68
+ for msg in pair:
69
+ with st.chat_message(msg["role"]):
70
+ st.write(msg["content"])
 
 
71
 
 
72
  if prompt:
73
  st.session_state.messages.append({"role": "user", "content": prompt})
74
 
75
  try:
76
+ # Create thread
77
  if st.session_state.thread_id is None:
78
  thread = client.beta.threads.create()
79
  st.session_state.thread_id = thread.id
80
 
81
+ # Send message to assistant
82
  client.beta.threads.messages.create(
83
  thread_id=st.session_state.thread_id,
84
  role="user",
85
  content=prompt
86
  )
87
 
88
+ # Run assistant
89
  run = client.beta.threads.runs.create(
90
  thread_id=st.session_state.thread_id,
91
  assistant_id=ASSISTANT_ID
92
  )
93
 
94
+ # Wait for completion
95
  with st.spinner("Assistant is thinking..."):
96
  while True:
97
  run_status = client.beta.threads.runs.retrieve(
 
102
  break
103
  time.sleep(1)
104
 
105
+ # Get assistant reply
106
  messages = client.beta.threads.messages.list(thread_id=st.session_state.thread_id)
107
  assistant_message = None
108
  for message in reversed(messages.data):
 
112
 
113
  st.session_state.messages.append({"role": "assistant", "content": assistant_message})
114
 
115
+ # βœ… Updated: Extract any GitHub-hosted .png image URL (flexible across repos)
116
  image_match = re.search(
117
+ r'https://raw\.githubusercontent\.com/AndrewLORTech/[a-zA-Z0-9_\-/]+\.png',
118
  assistant_message
119
  )
120
  if image_match:
121
  st.session_state.image_url = image_match.group(0)
122
  st.session_state.image_updated = True
123
 
124
+ st.rerun()
125
 
126
  except Exception as e:
127
  st.error(f"❌ Error: {str(e)}")