wiped commited on
Commit
bb7f31e
·
verified ·
1 Parent(s): 2e4dbd1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -51
app.py CHANGED
@@ -8,7 +8,7 @@ import urllib.request
8
  import urllib.parse
9
  from hashlib import sha256
10
 
11
- # ===== 1. CONFIG & MODEL (สมอง AI) =====
12
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
13
  EMBED_DIM, HIDDEN_DIM = 128, 256
14
 
@@ -24,103 +24,157 @@ class BataBrain(nn.Module):
24
  out, _ = self.lstm(embeds)
25
  return self.fc(out[:, -1, :])
26
 
27
- # ===== 2. AI CONTROLLER (ระบบคิดและสืบค้น) =====
28
  class BataAI:
29
  def __init__(self):
 
 
 
 
30
  if 'w2i' not in st.session_state:
31
  st.session_state.w2i = {"<PAD>": 0, "<START>": 1, "<END>": 2, "<UNK>": 3}
32
  st.session_state.i2w = ["<PAD>", "<START>", "<END>", "<UNK>"]
33
-
34
- self.init_model()
35
 
36
  def init_model(self):
37
  v_size = len(st.session_state.i2w)
38
  self.model = BataBrain(v_size).to(DEVICE)
39
  self.optimizer = optim.Adam(self.model.parameters(), lr=0.001)
40
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  def search_web(self, query):
42
  try:
43
- q = urllib.parse.quote(query + " คืออะไร ข้อมูลทางการ")
44
- url = f"https://www.google.com/search?q={q}"
45
- req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
46
- with urllib.request.urlopen(req) as res:
 
 
47
  html = res.read().decode('utf-8', errors='ignore')
48
- clean = re.sub(r'<[^>]+>', ' ', html)
49
- snippets = re.findall(r'[ก-๙a-zA-Z\s]{30,200}', clean)
50
- return " ".join(snippets[5:10])
51
- except: return ""
 
 
 
 
 
 
 
 
 
 
52
 
53
  def generate_formal_response(self, prompt):
 
 
54
  info = self.search_web(prompt)
55
- prefix = "เรียน ท่านผู้ใช้งาน จากการตรวจสอบข้อมูลเบื้องต้นพบว่า "
56
- body = info[:200] if info else "ข้อมูลดังกล่าวยังไม่ปรากฏในฐานระบบขณะนี้"
57
- suffix = "\n\nจึงเรียนมาเพื่อโปรดพิจารณา หากต้องการข้อมูลเพิ่มเติมกรุณาแจ้งดิฉันค่ะ"
58
- return prefix + body + suffix
 
 
 
 
 
 
 
 
59
 
60
- # ===== 3. DATABASE & AUTH (ระบบ Login) =====
61
  def init_db():
62
- conn = sqlite3.connect('bata_web.db')
63
  c = conn.cursor()
64
  c.execute('CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, password TEXT)')
65
  conn.commit()
66
  return conn
67
 
68
- # ===== 4. UI (หน้าเว็บ Streamlit) =====
69
  def main():
70
- st.set_page_config(page_title="Bata AI Corporate", page_icon="💅")
71
- st.title("👁️👄👁️ Bata AI: Corporate Web")
72
 
73
- init_db()
 
 
 
 
 
 
 
 
 
 
 
74
  ai = BataAI()
75
 
76
  if 'logged_in' not in st.session_state:
77
  st.session_state.logged_in = False
78
 
79
- # --- LOGIN PAGE ---
80
  if not st.session_state.logged_in:
81
- tab1, tab2 = st.tabs(["เข้าสู่ระบบ", "ลงทะเบียน"])
82
 
83
  with tab1:
84
- u = st.text_input("ชื่อผู้ใช้งาน", key="login_u")
85
- p = st.text_input("รหัสผ่าน", type="password", key="login_p")
86
- if st.button("Login"):
87
  hp = sha256(p.encode()).hexdigest()
88
- conn = init_db()
89
- c = conn.cursor()
90
  c.execute("SELECT * FROM users WHERE username=? AND password=?", (u, hp))
91
  if c.fetchone():
92
  st.session_state.logged_in = True
93
  st.session_state.user = u
 
94
  st.rerun()
95
- else: st.error("ข้อมูลไม่ถูกต้องค่ะแม่")
96
 
97
  with tab2:
98
  ru = st.text_input("ตั้งชื่อผู้ใช้งาน", key="reg_u")
99
  rp = st.text_input("ตั้งรหัสผ่าน", type="password", key="reg_p")
100
- if st.button("สมัครสมาชิก"):
101
- rhp = sha256(rp.encode()).hexdigest()
102
- try:
103
- conn = init_db()
104
- c = conn.cursor()
105
- c.execute("INSERT INTO users VALUES (?,?)", (ru, rhp))
106
- conn.commit()
107
- st.success("ลงทะเบียนสำเร็จแล้วค่ะ! เชิญไป Login")
108
- except: st.error("ชื่อนี้มีคนใช้แล้วค่ะตัวมัม")
109
-
110
- # --- CHAT PAGE ---
 
111
  else:
112
- st.sidebar.write(f"👤 ผู้ใช้งาน: **{st.session_state.user}**")
113
- if st.sidebar.button("Logout"):
114
- st.session_state.logged_in = False
115
- st.rerun()
 
 
 
 
116
 
117
- st.subheader("สนทนาภาษาทางการ")
118
- user_msg = st.text_input("พิมพ์คำถามของท่าน...", placeholder="เช่น AI คืออะไร?")
119
 
120
- if st.button("ส่งคำถาม"):
121
- with st.spinner('ดิฉันกำลังใช้สมองคิดอยู่ค่ะ...'):
122
- response = ai.generate_formal_response(user_msg)
123
- st.info(f"**Bata AI:** {response}")
 
 
 
 
124
 
125
  if __name__ == "__main__":
126
  main()
 
8
  import urllib.parse
9
  from hashlib import sha256
10
 
11
+ # ===== 1. CONFIG & MODEL (สมอง AI อัปเกรด) =====
12
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
13
  EMBED_DIM, HIDDEN_DIM = 128, 256
14
 
 
24
  out, _ = self.lstm(embeds)
25
  return self.fc(out[:, -1, :])
26
 
27
+ # ===== 2. AI CONTROLLER (ระบบกรองข้อมูลตัวแม่) =====
28
  class BataAI:
29
  def __init__(self):
30
+ self.init_vocab()
31
+ self.init_model()
32
+
33
+ def init_vocab(self):
34
  if 'w2i' not in st.session_state:
35
  st.session_state.w2i = {"<PAD>": 0, "<START>": 1, "<END>": 2, "<UNK>": 3}
36
  st.session_state.i2w = ["<PAD>", "<START>", "<END>", "<UNK>"]
 
 
37
 
38
  def init_model(self):
39
  v_size = len(st.session_state.i2w)
40
  self.model = BataBrain(v_size).to(DEVICE)
41
  self.optimizer = optim.Adam(self.model.parameters(), lr=0.001)
42
 
43
+ def clean_text(self, text):
44
+ """ระบบกำจัดขยะและรหัส Base64/HTML"""
45
+ # ลบ HTML tags
46
+ text = re.sub(r'<[^>]+>', ' ', text)
47
+ # ลบพวก Base64 หรือ String ยาวๆ ที่ไม่มีเว้นวรรค (ป้องกันรหัสแปลกๆ)
48
+ text = re.sub(r'[A-Za-z0-9+/]{50,}', '', text)
49
+ # ลบสัญลักษณ์พิเศษเยอะๆ
50
+ text = re.sub(r'[\{\}\[\]\(\)_=+\\\/#]', ' ', text)
51
+ # ลบเว้นวรรคซ้ำซ้อน
52
+ text = re.sub(r'\s+', ' ', text).strip()
53
+ return text
54
+
55
  def search_web(self, query):
56
  try:
57
+ # ค้นหาแบบเน้นนิยาม ภาษาไทย
58
+ q = urllib.parse.quote(f"สรุปความหมาย {query} คืออะไร")
59
+ url = f"https://www.google.com/search?q={q}&hl=th"
60
+ req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebkit/537.36'})
61
+
62
+ with urllib.request.urlopen(req, timeout=5) as res:
63
  html = res.read().decode('utf-8', errors='ignore')
64
+ cleaned = self.clean_text(html)
65
+
66
+ # ดึงเฉพาะประโยคที่มีภาษาไทยและดูเป็นเนื้อความ
67
+ sentences = re.findall(r'[ก-๙][ก-๙a-zA-Z0-9\s\.\,]{20,150}', cleaned)
68
+
69
+ # คัดกรองคำตอบที่ดีที่สุด 3-4 ประโยค
70
+ good_info = []
71
+ for s in sentences:
72
+ if any(word in s for word in [query, "คือ", "หมายถึง", "เป็น"]):
73
+ good_info.append(s.strip())
74
+
75
+ return " ".join(good_info[:3])
76
+ except:
77
+ return ""
78
 
79
  def generate_formal_response(self, prompt):
80
+ if not prompt: return "กรุณาระบุคำถามที่ท่านต้องการทราบค่ะ"
81
+
82
  info = self.search_web(prompt)
83
+
84
+ # ส่วนประกอบคำตอบแบบ Corporate
85
+ header = f"📋 **รายงานสรุปข้อมูลเรื่อง: {prompt}**\n\n"
86
+ prefix = "เรียน ท่านผู้ใช้งาน จากการตรวจสอบฐานข้อมูลและแหล่งสืบค้นพบว่า: \n\n> "
87
+
88
+ if info and len(info) > 10:
89
+ body = info
90
+ else:
91
+ body = "ขณะนี้ระบบกำลังปรับปรุงฐานข้อมูลเชิงลึกสำหรับหัวข้อนี้ อย่างไรก็ตามเบื้องต้นแนะนำให้ท่านตรวจสอบผ่านเอกสารอ้างอิงหลักขององค์กรอีกครั้งค่ะ"
92
+
93
+ footer = "\n\nจึงเรียนมาเพื่อโปรดทราบและพิจารณาดำเนินการในส่วนที่เกี่ยวข้องค่ะ 💅"
94
+ return header + prefix + body + footer
95
 
96
+ # ===== 3. DATABASE & AUTH =====
97
  def init_db():
98
+ conn = sqlite3.connect('bata_web.db', check_same_thread=False)
99
  c = conn.cursor()
100
  c.execute('CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, password TEXT)')
101
  conn.commit()
102
  return conn
103
 
104
+ # ===== 4. UI (หน้าเว็บตัวมัม) =====
105
  def main():
106
+ st.set_page_config(page_title="Bata AI Corporate v2", page_icon="💅", layout="centered")
 
107
 
108
+ # Custom CSS ให้ดูแพง
109
+ st.markdown("""
110
+ <style>
111
+ .stButton>button { width: 100%; border-radius: 20px; background-color: #ff4b4b; color: white; }
112
+ .stTextInput>div>div>input { border-radius: 15px; }
113
+ </style>
114
+ """, unsafe_allow_html=True)
115
+
116
+ st.title("👁️👄👁️ Bata AI: Corporate v2")
117
+ st.caption("ระบบปัญญาประดิษฐ์สืบค้นข้อมูลเชิงวิชาการและธุรกิจ")
118
+
119
+ db_conn = init_db()
120
  ai = BataAI()
121
 
122
  if 'logged_in' not in st.session_state:
123
  st.session_state.logged_in = False
124
 
 
125
  if not st.session_state.logged_in:
126
+ tab1, tab2 = st.tabs(["🔒 เข้าสู่ระบบ", "📝 ลงทะเบียน"])
127
 
128
  with tab1:
129
+ u = st.text_input("Username", placeholder="ระบุชื่อผู้ใช้งาน", key="login_u")
130
+ p = st.text_input("Password", type="password", placeholder="ระบุรหัสผ่าน", key="login_p")
131
+ if st.button("เข้าสู่ระบบ"):
132
  hp = sha256(p.encode()).hexdigest()
133
+ c = db_conn.cursor()
 
134
  c.execute("SELECT * FROM users WHERE username=? AND password=?", (u, hp))
135
  if c.fetchone():
136
  st.session_state.logged_in = True
137
  st.session_state.user = u
138
+ st.success(f"ยินดีต้อนรับคุณ {u} ค่ะ!")
139
  st.rerun()
140
+ else: st.error("ข้อมูลไม่ถูกต้องค่ะคุณแม่ เช็คอีกรอบซิ!")
141
 
142
  with tab2:
143
  ru = st.text_input("ตั้งชื่อผู้ใช้งาน", key="reg_u")
144
  rp = st.text_input("ตั้งรหัสผ่าน", type="password", key="reg_p")
145
+ if st.button("ยืนยันการสมัคร"):
146
+ if len(ru) < 3 or len(rp) < 4:
147
+ st.warning("ชื่อหรือรหัสผ่านสั้นเกินไปนะคะ เดี๋ยวคนอื่นเดาง่ายค่ะ!")
148
+ else:
149
+ rhp = sha256(rp.encode()).hexdigest()
150
+ try:
151
+ c = db_conn.cursor()
152
+ c.execute("INSERT INTO users VALUES (?,?)", (ru, rhp))
153
+ db_conn.commit()
154
+ st.success("ลงทะเบียนสำเร็จ! เชิญไปหน้าเข้าสู่ระบบค่ะ")
155
+ except: st.error("ชื่อนี้มีคนสวยใช้ไปแล้วค่ะ!")
156
+
157
  else:
158
+ # หน้า Chat
159
+ with st.sidebar:
160
+ st.write(f"💼 **สถานะ:** กำลังปฏิบัติงาน")
161
+ st.write(f"👤 **บัญชี:** {st.session_state.user}")
162
+ st.divider()
163
+ if st.button("ออกจากระบบ (Logout)"):
164
+ st.session_state.logged_in = False
165
+ st.rerun()
166
 
167
+ st.subheader("📝 สอบถามข้อมูลเชิงวิชาการ")
168
+ user_msg = st.text_input("หัวข้อที่ต้องการสืบค้น:", placeholder="เช่น สกุลเงินดิจิทัล, ภาวะโลกร้อน...")
169
 
170
+ if st.button("วิเคราะห์ข้อมูล"):
171
+ if user_msg:
172
+ with st.spinner('ดิฉันกำลังประมวลผลข้อมูลระดับ High-End อยู่ค่ะ...'):
173
+ response = ai.generate_formal_response(user_msg)
174
+ st.markdown("---")
175
+ st.write(response)
176
+ else:
177
+ st.warning("ใส่หัวข้อก่อนสิคะแม่!")
178
 
179
  if __name__ == "__main__":
180
  main()