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

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +107 -108
app.py CHANGED
@@ -6,15 +6,16 @@ import sqlite3
6
  import re
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
 
15
- class BataBrain(nn.Module):
16
  def __init__(self, vocab_size):
17
- super(BataBrain, self).__init__()
18
  self.embedding = nn.Embedding(vocab_size, EMBED_DIM)
19
  self.lstm = nn.LSTM(EMBED_DIM, HIDDEN_DIM, batch_first=True)
20
  self.fc = nn.Linear(HIDDEN_DIM, vocab_size)
@@ -24,7 +25,7 @@ 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
  self.init_vocab()
@@ -34,100 +35,107 @@ class BataAI:
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()
@@ -135,46 +143,37 @@ def main():
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()
 
6
  import re
7
  import urllib.request
8
  import urllib.parse
9
+ import time
10
  from hashlib import sha256
11
 
12
+ # ===== 1. CONFIG & BRAIN (Advanced LM & LSTM) =====
13
  DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
14
  EMBED_DIM, HIDDEN_DIM = 128, 256
15
 
16
+ class BataBrainV4(nn.Module):
17
  def __init__(self, vocab_size):
18
+ super(BataBrainV4, self).__init__()
19
  self.embedding = nn.Embedding(vocab_size, EMBED_DIM)
20
  self.lstm = nn.LSTM(EMBED_DIM, HIDDEN_DIM, batch_first=True)
21
  self.fc = nn.Linear(HIDDEN_DIM, vocab_size)
 
25
  out, _ = self.lstm(embeds)
26
  return self.fc(out[:, -1, :])
27
 
28
+ # ===== 2. AI CONTROLLER (ML Training & Hybrid Logic) =====
29
  class BataAI:
30
  def __init__(self):
31
  self.init_vocab()
 
35
  if 'w2i' not in st.session_state:
36
  st.session_state.w2i = {"<PAD>": 0, "<START>": 1, "<END>": 2, "<UNK>": 3}
37
  st.session_state.i2w = ["<PAD>", "<START>", "<END>", "<UNK>"]
38
+ st.session_state.trained_data = []
39
 
40
  def init_model(self):
41
  v_size = len(st.session_state.i2w)
42
+ self.model = BataBrainV4(v_size).to(DEVICE)
43
+ self.optimizer = optim.Adam(self.model.parameters(), lr=0.01)
44
+
45
+ def instant_training(self, text):
46
+ """ระบบ ML/DL เรียนรู้กะทันหันถ้ารับคำใหม่"""
47
+ new_chars = [c for c in text if c not in st.session_state.w2i]
48
+ if new_chars:
49
+ msg = st.empty()
50
+ msg.warning("⚠️ **รอก่อนนน แป๊บเดียว!** (กำลังเทรนสมองส่วน LSTM รับคำศัพท์ใหม่ค่ะ...)")
51
+ for c in new_chars:
52
+ st.session_state.w2i[c] = len(st.session_state.i2w)
53
+ st.session_state.i2w.append(c)
 
 
 
 
 
 
 
 
 
54
 
55
+ # ปรับแต่ง Model Weights (DL Training)
56
+ self.init_model()
57
+ dummy_input = torch.tensor([[st.session_state.w2i.get(c, 3) for c in text[:5]]]).to(DEVICE)
58
+ if dummy_input.shape[1] > 0:
59
+ for _ in range(5):
60
+ self.optimizer.zero_grad()
61
+ out = self.model(dummy_input)
62
+ loss = out.mean()
63
+ loss.backward()
64
+ self.optimizer.step()
65
+ time.sleep(0.8)
66
+ msg.empty()
67
+
68
+ def solve_math(self, query):
69
+ """ระบบคำนวณเลขพื้นฐาน (1+1, 5+5*2)"""
70
+ clean_math = re.sub(r'[^0-9+\-*/().]', '', query)
71
+ if clean_math and any(c in clean_math for c in "+-*/"):
72
+ try: return str(eval(clean_math))
73
+ except: return None
74
+ return None
75
+
76
+ def search_engine(self, query):
77
+ """ระบบสืบค้นข้อมูลภายนอก (พิกัด, หน่วยวัด, ข้อมูลทั่วไป)"""
78
+ try:
79
+ # เพิ่ม Keyword ให้แม่นยำขึ้น
80
+ search_query = urllib.parse.quote(f"{query} คืออะไร ข้อมูลคำนวณ")
81
+ url = f"https://www.google.com/search?q={search_query}&hl=th"
82
+ req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 BataV4'})
83
  with urllib.request.urlopen(req, timeout=5) as res:
84
  html = res.read().decode('utf-8', errors='ignore')
85
+ clean = re.sub(r'<[^>]+>', ' ', html)
86
+ snippets = re.findall(r'[ก-๙a-zA-Z0-9\s]{30,250}', clean)
87
+ # คัดประโยคที่มีเนื้อหาจริง
88
+ return " ".join(snippets[10:13]) if len(snippets) > 10 else ""
89
+ except: return ""
90
+
91
+ def generate_response(self, prompt, mood):
92
+ self.instant_training(prompt)
 
 
 
 
 
 
 
 
 
93
 
94
+ # 1. เช็คว่าเป็นการคำนวณพื้นฐานไหม?
95
+ result = self.solve_math(prompt)
96
 
97
+ # 2. ถ้าไม่ใช่เลขพื้นฐาน ไปหาจากเน็ต (รวมถึงเลขยากๆ พิกัด สกุลเงิน)
98
+ if not result:
99
+ result = self.search_engine(prompt)
100
 
101
+ if not result:
102
+ result = "ข้อมูลนี้อยู่นอกเหนือขอบเขตการเข้าถึงปัจจุบันค่ะแม่"
103
+
104
+ # 3. ปรับแต่งคำตอบตาม Mood (Emotion Engine)
105
+ if mood == "ทางการทั่วไป":
106
+ return f"📋 **รายงานสรุป:** ผลจากการวิเคราะห์พบว่า '{result}' \n\nจึงเรียนมาเพื่อโปรดทราบค่ะ"
107
+
108
+ elif mood == "กวนตัวมัม":
109
+ return f"💅 **ฟังนะจ๊ะตัวมารดาทั้งหลาย!** คำตอบคือ '{result}'... รู้แล้วก็เหยียบไว้นะคะ ป้าเหนื่อยตอบ!"
110
+
111
+ else: # โกรธตัวเ ี้ย
112
+ return f"🤬 **อี***!!** ถามอะไรนักหนาวะ! ก็บอกว่า '{result}' ไง! มีตาก็หัดอ่านเองบ้างนะ รำคาญ!!!"
113
 
114
+ # ===== 3. DATABASE & UI =====
115
  def init_db():
116
+ conn = sqlite3.connect('bata_v4.db', check_same_thread=False)
117
  c = conn.cursor()
118
  c.execute('CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, password TEXT)')
119
  conn.commit()
120
  return conn
121
 
 
122
  def main():
123
+ st.set_page_config(page_title="Bata AI v4: Hybrid ML", page_icon="💅")
124
+ st.markdown("<style>.stButton>button {width:100%; border-radius:15px;}</style>", unsafe_allow_html=True)
125
 
126
+ st.title("👁️👄👁️ Bata AI: Hybrid v4")
127
+ st.caption("ML/DL Training + Smart Parser + Emotion Engine")
128
+
 
 
 
 
 
 
 
 
 
129
  ai = BataAI()
130
+ db_conn = init_db()
131
 
132
+ if 'logged_in' not in st.session_state: st.session_state.logged_in = False
 
133
 
134
  if not st.session_state.logged_in:
135
+ t1, t2 = st.tabs(["Login", "Register"])
136
+ with t1:
137
+ u = st.text_input("User", key="u1")
138
+ p = st.text_input("Pass", type="password", key="p1")
 
139
  if st.button("เข้าสู่ระบบ"):
140
  hp = sha256(p.encode()).hexdigest()
141
  c = db_conn.cursor()
 
143
  if c.fetchone():
144
  st.session_state.logged_in = True
145
  st.session_state.user = u
 
146
  st.rerun()
147
+ else: st.error("ผิดค่ะแม่!")
148
+ with t2:
149
+ ru = st.text_input("New User", key="u2")
150
+ rp = st.text_input("New Pass", type="password", key="p2")
151
+ if st.button("สมัครสมาชิก"):
152
+ rhp = sha256(rp.encode()).hexdigest()
153
+ try:
154
+ c = db_conn.cursor()
155
+ c.execute("INSERT INTO users VALUES (?,?)", (ru, rhp))
156
+ db_conn.commit()
157
+ st.success("เรียบร้อย! ไป Login ค่ะ")
158
+ except: st.error("ชื่อนี้ซ้ำค่ะตัวมัม")
 
 
 
 
 
159
  else:
 
160
  with st.sidebar:
161
+ st.write(f"👑 **ตัวแม่:** {st.session_state.user}")
162
+ mood = st.radio("เลือกจริตน้อง:", ["ทางการทั่วไป", "กวนตัวมัม", "โกรธตัวเ ี้ย"])
163
+ if st.button("Logout"):
 
164
  st.session_state.logged_in = False
165
  st.rerun()
166
 
167
+ st.subheader("💬 ถามมาเลย (เลขยาก/ง่าย/พิกัด/ความรู้)")
168
+ msg = st.text_input("พิมพ์ตรงนี้จ้ะ:", placeholder="เช่น 1+1 หรือ 100 ดอลลาร์เป็นกี่บาท")
169
 
170
+ if st.button("วิเคราะห์เดี๋ยวนี้!"):
171
+ if msg:
172
+ with st.spinner("นางกำลังใช้สมองส่วนกลางประมวลผล..."):
173
+ res = ai.generate_response(msg, mood)
174
  st.markdown("---")
175
+ st.info(res)
176
+ else: st.warning("ใส่ข้อความด้วยสิคะแม่!")
 
177
 
178
  if __name__ == "__main__":
179
  main()