amornpan commited on
Commit
3d78302
·
verified ·
1 Parent(s): c3a94d8

Upload app.py

Browse files
Files changed (1) hide show
  1. app.py +163 -0
app.py ADDED
@@ -0,0 +1,163 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import streamlit as st
2
+ import requests
3
+ from datetime import datetime
4
+ import base64
5
+ import fitz # PyMuPDF
6
+ import os
7
+ import re
8
+
9
+ # ตรวจสอบและกำหนดค่าเริ่มต้นให้ st.session_state.dialog_done
10
+ if "dialog_done" not in st.session_state:
11
+ st.session_state.dialog_done = False # ค่าเริ่มต้นเป็น False
12
+
13
+ # ถ้า dialog_done เป็น False ให้แสดงหน้าคำถาม
14
+ if not st.session_state.dialog_done:
15
+ st.title("เริ่มต้นคำถาม")
16
+ st.write("คำถาม: ใครคือคนที่หน้าตาดีที่สุด?")
17
+
18
+ answer = st.text_input("กรุณาตอบคำถามนี้:")
19
+ if st.button("ส่งคำตอบ"): # ปุ่มส่งคำตอบ
20
+ if answer == "พี่ก้องคนหล่อ":
21
+ st.session_state.dialog_done = True # อัปเดตสถานะเป็น True
22
+ st.success("คำตอบถูกต้อง! กดปุ่ม 'เข้าสู่หน้าหลัก' เพื่อดำเนินการต่อ")
23
+ else:
24
+ st.error("คำตอบไม่ถูกต้อง กรุณาลองใหม่อีกครั้ง.")
25
+
26
+ if st.session_state.dialog_done:
27
+ # เพิ่มปุ่มเพื่อให้ผู้ใช้กดเข้าสู่หน้าหลัก
28
+ if st.button("เข้าสู่หน้าหลัก"):
29
+ st.experimental_rerun() # รีเฟรชเพื่อแสดงหน้าหลัก
30
+
31
+ else:
32
+ # เนื้อหาของหน้าหลัก
33
+ st.title("AI สนับสนุนความรู้ด้าน PDPA")
34
+ st.write("เราสอบถาม AI สืบค้น และสรุป")
35
+
36
+ # Define system prompt at the top level
37
+ system_prompt = """คุณเป็นผู้ช่วยที่มีความรู้ด้านกฎหมาย PDPA และสามารถให้คำตอบที่เกี่ยวข้องเฉพาะตาม context ที่ได้รับ"""
38
+
39
+ def clean_text_for_search(text):
40
+ """Clean text for better search matching"""
41
+ text = re.sub(r'P-\d+\s*$', '', text, flags=re.MULTILINE)
42
+ text = re.sub(r'Confidential.*$', '', text, flags=re.MULTILINE)
43
+ text = ' '.join(text.split())
44
+ return text
45
+
46
+ def create_highlighted_pdf(pdf_path, search_text, page_number):
47
+ """Create a highlighted version of the PDF page"""
48
+ try:
49
+ search_text = clean_text_for_search(search_text)
50
+ doc = fitz.open(pdf_path)
51
+ page = doc[int(page_number) - 1]
52
+ words = [word for word in search_text.split() if word]
53
+
54
+ for word in words:
55
+ if len(word) > 3:
56
+ text_instances = page.search_for(word)
57
+ for inst in text_instances:
58
+ highlight = page.add_highlight_annot(inst)
59
+ highlight.set_colors(stroke=(1, 1, 0))
60
+ highlight.update()
61
+
62
+ new_doc = fitz.open()
63
+ new_doc.insert_pdf(doc, from_page=int(page_number) - 1, to_page=int(page_number) - 1)
64
+ pdf_bytes = new_doc.write()
65
+
66
+ doc.close()
67
+ new_doc.close()
68
+
69
+ return pdf_bytes
70
+
71
+ except Exception as e:
72
+ st.error(f"Error in create_highlighted_pdf: {str(e)}")
73
+ return None
74
+
75
+ def format_file_size(size_in_bytes):
76
+ """Convert bytes to human readable format"""
77
+ for unit in ['B', 'KB', 'MB', 'GB']:
78
+ if size_in_bytes < 1024:
79
+ return f"{size_in_bytes:.2f} {unit}"
80
+ size_in_bytes /= 1024
81
+ return f"{size_in_bytes:.2f} GB"
82
+
83
+ def display_search_result(result, index):
84
+ """Display a single search result with metadata in an expander"""
85
+ with st.expander(f"🔍 Search Result #{index + 1} (Score: {result['score']:.4f})"):
86
+ st.markdown("#### 📄 Document Information")
87
+ col1, col2 = st.columns(2)
88
+
89
+ with col1:
90
+ st.markdown("**File Details:**")
91
+ st.write(f"• File Name: {result['metadata']['file_name']}")
92
+ st.write(f"• Page: {result['metadata']['page_label']}")
93
+ st.write(f"• Type: {result['metadata']['file_type']}")
94
+ st.write(f"• Size: {format_file_size(result['metadata']['file_size'])}")
95
+
96
+ with col2:
97
+ st.markdown("**Dates:**")
98
+ st.write(f"• Created: {result['metadata']['creation_date']}")
99
+ st.write(f"• Modified: {result['metadata']['last_modified_date']}")
100
+
101
+ st.markdown("#### 📝 Content")
102
+ st.markdown(f"```\n{result['text']}\n```")
103
+
104
+ st.markdown("#### 📂 File Location")
105
+ st.code(result['file_path'], language='plaintext')
106
+
107
+ try:
108
+ pdf_path = result['file_path']
109
+ if os.path.exists(pdf_path):
110
+ st.markdown("#### 📄 PDF Preview (with highlighted text)")
111
+
112
+ highlighted_pdf = create_highlighted_pdf(
113
+ pdf_path,
114
+ result['text'],
115
+ result['metadata']['page_label']
116
+ )
117
+
118
+ if highlighted_pdf:
119
+ base64_pdf = base64.b64encode(highlighted_pdf).decode('utf-8')
120
+ pdf_display = f'''
121
+ <iframe
122
+ src="data:application/pdf;base64,{base64_pdf}"
123
+ width="100%"
124
+ height="800px"
125
+ type="application/pdf"
126
+ style="border: 1px solid #ccc; border-radius: 5px;"
127
+ ></iframe>
128
+ '''
129
+ st.markdown(pdf_display, unsafe_allow_html=True)
130
+ else:
131
+ st.error("Failed to create highlighted PDF")
132
+ else:
133
+ st.error("PDF file not found at the specified location.")
134
+ except Exception as e:
135
+ st.error(f"Error displaying PDF: {str(e)}")
136
+
137
+ if "chat_history" not in st.session_state:
138
+ st.session_state.chat_history = []
139
+
140
+ with st.form(key="input_form"):
141
+ user_input = st.text_input("You:", key="input")
142
+ submit_button = st.form_submit_button("Send")
143
+
144
+ if submit_button:
145
+ if user_input:
146
+ if st.session_state.chat_history:
147
+ st.session_state.chat_history.insert(0, ("###", "###"))
148
+ st.session_state.chat_history.insert(0, ("You", user_input))
149
+
150
+ try:
151
+ response = requests.post("http://113.53.253.50:8002/search", json={"query": user_input})
152
+ response.raise_for_status()
153
+ data = response.json()
154
+ search_results = data["results"]
155
+
156
+ st.markdown("### 🔎 Search Results")
157
+ for idx, result in enumerate(search_results):
158
+ display_search_result(result, idx)
159
+
160
+ response_text = "\n\n---\n\n".join([f"Text: {result['text']}\nFile Path: {result['file_path']}" for result in search_results])
161
+
162
+ except requests.RequestException as e:
163
+ st.error(f"Error: {str(e)}")