IAMTFRMZA commited on
Commit
6aa98b4
ยท
verified ยท
1 Parent(s): beed6a9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +62 -67
app.py CHANGED
@@ -1,97 +1,92 @@
1
  import gradio as gr
 
2
  import os
3
  import json
4
- from openai import OpenAI
5
 
6
- # ========== Config ==========
7
- OPENAI_API_KEY = os.environ.get("OPENAI_API_KEY")
8
  ASSISTANT_ID = os.environ.get("ASSISTANT_ID")
9
- client = OpenAI(api_key=OPENAI_API_KEY)
10
 
11
- # ========== Functions ==========
12
- def query_assistant(message):
13
  try:
14
- thread = client.beta.threads.create()
15
- client.beta.threads.messages.create(
16
  thread_id=thread.id,
17
  role="user",
18
- content=message
19
  )
20
- run = client.beta.threads.runs.create(
 
21
  thread_id=thread.id,
22
- assistant_id=ASSISTANT_ID
 
 
23
  )
24
 
25
- # Poll run status
26
  while True:
27
- run_status = client.beta.threads.runs.retrieve(
28
- thread_id=thread.id,
29
- run_id=run.id
30
- )
31
- if run_status.status in ("completed", "failed", "cancelled"):
32
  break
33
 
34
  if run_status.status != "completed":
35
- return f"โŒ Assistant failed: {run_status.status}", []
36
 
37
- messages = client.beta.threads.messages.list(thread_id=thread.id)
38
  for m in reversed(messages.data):
39
  if m.role == "assistant":
 
40
  try:
41
- parsed = json.loads(m.content[0].text.value)
42
- return None, parsed.get("results", [])
 
 
 
 
 
 
 
 
 
 
 
 
 
 
43
  except Exception as e:
44
- return f"โš ๏ธ Failed to parse assistant response: {e}", []
45
- return "โš ๏ธ No assistant response found", []
46
- except Exception as e:
47
- return f"โŒ Error: {e}", []
48
 
49
- def render_cards(results):
50
- cards = []
51
- for r in results:
52
- title = r.get("drawing_title", "Untitled")
53
- summary = r.get("summary", "")
54
- pages = r.get("pages", [])
55
- image_elems = []
56
- for page in pages:
57
- url = page.get("public_image_url")
58
- label = f"{title} โ€“ Page {page.get('page_number')}"
59
- if url:
60
- image_elems.append(gr.Image(value=url, label=label, show_label=True))
61
 
62
- with gr.Column(scale=1):
63
- cards.append(
64
- gr.Group(
65
- [
66
- gr.Markdown(f"**{title}**\n\n**Summary:** {summary}"),
67
- gr.Accordion("๐Ÿ“‚ View Drawing Pages", open=False, children=image_elems)
68
- ]
69
- )
70
- )
71
- return cards
72
 
73
- def on_query_submit(prompt):
74
- status, results = query_assistant(prompt)
75
- if status:
76
- return status, []
77
- return "โœ… Found matching drawings", render_cards(results)
 
78
 
79
- # ========== Interface ==========
80
- with gr.Blocks(theme=gr.themes.Base(), title="Forrestdale Technical Drawing Assistant") as app:
81
- gr.Markdown("""
82
- # ๐Ÿ—๏ธ Forrestdale Technical Drawing Assistant
83
- Ask about plans, drawings or components (e.g. _Show me all electrical plans_)
84
- """)
85
 
86
- with gr.Row():
87
- query_input = gr.Textbox(placeholder="e.g. Show me all civil drainage plans", scale=5)
88
- query_button = gr.Button("๐Ÿ” Search", scale=1)
89
 
90
- status_output = gr.Markdown("", visible=True)
91
- result_display = gr.Column()
 
 
 
92
 
93
- query_button.click(fn=on_query_submit, inputs=query_input, outputs=[status_output, result_display])
94
 
95
- # ========== Launch ==========
96
- if __name__ == "__main__":
97
- app.launch()
 
1
  import gradio as gr
2
+ import openai
3
  import os
4
  import json
 
5
 
6
+ # === Load Secrets ===
7
+ openai.api_key = os.environ.get("OPENAI_API_KEY")
8
  ASSISTANT_ID = os.environ.get("ASSISTANT_ID")
9
+ VECTOR_STORE_ID = "vs_68199dddd40c8191973e8a6d1b136cd3"
10
 
11
+ # === Chat Function ===
12
+ def search_drawings(user_query):
13
  try:
14
+ thread = openai.beta.threads.create()
15
+ openai.beta.threads.messages.create(
16
  thread_id=thread.id,
17
  role="user",
18
+ content=user_query
19
  )
20
+
21
+ run = openai.beta.threads.runs.create(
22
  thread_id=thread.id,
23
+ assistant_id=ASSISTANT_ID,
24
+ tool_choice="auto",
25
+ vector_store_ids=[VECTOR_STORE_ID]
26
  )
27
 
28
+ # Wait for completion
29
  while True:
30
+ run_status = openai.beta.threads.runs.retrieve(thread_id=thread.id, run_id=run.id)
31
+ if run_status.status in ["completed", "failed", "cancelled"]:
 
 
 
32
  break
33
 
34
  if run_status.status != "completed":
35
+ return gr.update(visible=True), f"โŒ Assistant failed: {run_status.status}", []
36
 
37
+ messages = openai.beta.threads.messages.list(thread_id=thread.id)
38
  for m in reversed(messages.data):
39
  if m.role == "assistant":
40
+ raw = m.content[0].text.value
41
  try:
42
+ result = json.loads(raw)
43
+ cards = []
44
+ for entry in result.get("drawings", []):
45
+ img_tag = f'<img src="{entry["image_url"]}" style="width:100%; border-radius:12px"/>'
46
+ page_caption = f"{entry['drawing_number']} โ€“ Page {entry['page_number']}"
47
+ summary = f"<b>Summary:</b> {entry['summary']}"
48
+
49
+ with gr.Column(scale=1):
50
+ cards.append(gr.HTML(f"""
51
+ <div style='background:#1a1a1a; border:1px solid #333; border-radius:14px; padding:16px; height:100%'>
52
+ {img_tag}<br>
53
+ <p style='margin-top:8px; font-weight:bold;'>{page_caption}</p>
54
+ <p style='font-size:14px'>{summary}</p>
55
+ </div>
56
+ """))
57
+ return gr.update(visible=False), "", cards
58
  except Exception as e:
59
+ return gr.update(visible=True), "โš ๏ธ Could not parse assistant response as JSON.", []
60
+ return gr.update(visible=True), "โš ๏ธ No assistant response found.", []
 
 
61
 
62
+ except Exception as e:
63
+ return gr.update(visible=True), f"โŒ Error: {str(e)}", []
 
 
 
 
 
 
 
 
 
 
64
 
65
+ # === UI ===
66
+ title = "\U0001F5A9 Forrestdale Technical Drawing Assistant"
67
+ description = "Ask for plans by discipline, components or tags (e.g. \"Show all architectural plans\")"
 
 
 
 
 
 
 
68
 
69
+ def ui():
70
+ with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
71
+ gr.Markdown(f"""
72
+ <h1 style='font-size:32px'>{title}</h1>
73
+ <p style='color:#aaa; font-size:16px'>{description}</p>
74
+ """)
75
 
76
+ with gr.Row():
77
+ query_input = gr.Textbox(placeholder="e.g. Show all electrical plans", scale=4)
78
+ submit_btn = gr.Button("Search", variant="primary", scale=1)
 
 
 
79
 
80
+ error_box = gr.Markdown("", visible=False)
81
+ result_gallery = gr.Group([])
 
82
 
83
+ submit_btn.click(
84
+ fn=search_drawings,
85
+ inputs=[query_input],
86
+ outputs=[error_box, error_box, result_gallery]
87
+ )
88
 
89
+ return demo
90
 
91
+ app = ui()
92
+ app.launch()