Update app.py
Browse files
app.py
CHANGED
|
@@ -7,10 +7,11 @@ import re
|
|
| 7 |
import urllib.request
|
| 8 |
import urllib.parse
|
| 9 |
import time
|
|
|
|
| 10 |
from datetime import datetime, timedelta
|
| 11 |
from hashlib import sha256
|
| 12 |
|
| 13 |
-
# ===== 1. BRAIN ARCHITECTURE (
|
| 14 |
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 15 |
EMBED_DIM, HIDDEN_DIM = 128, 256
|
| 16 |
|
|
@@ -26,7 +27,7 @@ class BataLanguageModel(nn.Module):
|
|
| 26 |
out, _ = self.lstm(embeds)
|
| 27 |
return self.fc(out[:, -1, :])
|
| 28 |
|
| 29 |
-
# ===== 2. AI CONTROLLER (
|
| 30 |
class BataAI:
|
| 31 |
def __init__(self):
|
| 32 |
self.init_vocab()
|
|
@@ -44,81 +45,105 @@ class BataAI:
|
|
| 44 |
self.optimizer = optim.Adam(self.model.parameters(), lr=0.01)
|
| 45 |
|
| 46 |
def online_training(self, text):
|
| 47 |
-
"""ระบบ ML/DL เรียนรู้กะทันหันระหว่างตอบ"""
|
| 48 |
new_chars = [c for c in text if c not in st.session_state.w2i]
|
| 49 |
if new_chars:
|
| 50 |
msg = st.empty()
|
| 51 |
-
msg.warning("⚠️ **รอก่อนนน แป๊บเดียว!** (
|
| 52 |
for c in new_chars:
|
| 53 |
st.session_state.w2i[c] = len(st.session_state.i2w)
|
| 54 |
st.session_state.i2w.append(c)
|
| 55 |
-
self.init_model()
|
| 56 |
-
time.sleep(1.
|
| 57 |
msg.empty()
|
| 58 |
st.session_state.trained_count += 1
|
| 59 |
|
| 60 |
-
def
|
| 61 |
-
"""
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
try:
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
elif any(x in query for x in ['ตารางวา', 'แปลงหน่วย', 'พิกัด', 'เงิน']):
|
| 72 |
-
q_param = f"วิธีคำนวณหรือข้อมูลของ {query}"
|
| 73 |
-
else:
|
| 74 |
-
q_param = query
|
| 75 |
-
|
| 76 |
-
url = f"https://www.google.com/search?q={urllib.parse.quote(q_param)}&hl=th"
|
| 77 |
-
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0 Bata-AI-V5'})
|
| 78 |
with urllib.request.urlopen(req, timeout=5) as res:
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
found = re.findall(r'[ก-๙]{
|
| 82 |
-
|
| 83 |
-
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
def get_thai_time(self):
|
| 86 |
return (datetime.utcnow() + timedelta(hours=7)).strftime("%H:%M:%S")
|
| 87 |
|
| 88 |
def generate_response(self, prompt, mood):
|
| 89 |
-
self.online_training(prompt)
|
| 90 |
|
| 91 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
if re.match(r'^[0-9+\-*/().\s]+$', prompt):
|
| 93 |
-
try: info = f"
|
| 94 |
-
except: info = self.
|
| 95 |
else:
|
| 96 |
-
info = self.
|
| 97 |
|
| 98 |
t_time = self.get_thai_time()
|
| 99 |
|
| 100 |
-
#
|
| 101 |
if mood == "ทางการทั่วไป":
|
| 102 |
-
return f"📊 **รายงาน:** {info}\n\n[บันทึก
|
| 103 |
elif mood == "กวนตัวมัม":
|
| 104 |
-
return f"💅 **ฟังนะ
|
| 105 |
-
else: # โกรธตัวเ
|
| 106 |
-
return f"🤬 **อี***!** {info[:
|
| 107 |
|
| 108 |
-
# ===== 3. UI & AUTH =====
|
| 109 |
def init_db():
|
| 110 |
-
conn = sqlite3.connect('
|
| 111 |
c = conn.cursor()
|
| 112 |
c.execute('CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, password TEXT)')
|
| 113 |
conn.commit()
|
| 114 |
return conn
|
| 115 |
|
| 116 |
def main():
|
| 117 |
-
st.set_page_config(page_title="Bata AI:
|
| 118 |
st.markdown("<style>.stButton>button {width:100%; background-color:#ff4b4b; color:white;}</style>", unsafe_allow_html=True)
|
| 119 |
|
| 120 |
-
st.title("👁️👄👁️ Bata AI:
|
| 121 |
-
st.caption(f"🕒
|
| 122 |
|
| 123 |
db_conn = init_db()
|
| 124 |
ai = BataAI()
|
|
@@ -137,31 +162,31 @@ def main():
|
|
| 137 |
if c.fetchone():
|
| 138 |
st.session_state.logged_in, st.session_state.user = True, u
|
| 139 |
st.rerun()
|
| 140 |
-
else: st.error("ผิดค่ะแม่!")
|
| 141 |
with t2:
|
| 142 |
ru = st.text_input("New Username")
|
| 143 |
rp = st.text_input("New Password", type="password")
|
| 144 |
if st.button("สมัครสมาชิก"):
|
| 145 |
try:
|
| 146 |
c = db_conn.cursor(); c.execute("INSERT INTO users VALUES (?,?)", (ru, sha256(rp.encode()).hexdigest()))
|
| 147 |
-
db_conn.commit(); st.success("ส
|
| 148 |
-
except: st.error("ชื่อ
|
| 149 |
else:
|
| 150 |
with st.sidebar:
|
| 151 |
st.header(f"👤 {st.session_state.user}")
|
| 152 |
-
st.metric("สมองเรียนรู้ไปแล้ว", f"{st.session_state.trained_count} ครั้ง")
|
| 153 |
-
mood = st.radio("เลือกจริต
|
| 154 |
if st.button("Logout"):
|
| 155 |
st.session_state.logged_in = False
|
| 156 |
st.rerun()
|
| 157 |
|
| 158 |
-
user_msg = st.text_input("
|
| 159 |
-
if st.button("
|
| 160 |
if user_msg:
|
| 161 |
-
with st.spinner('กำลัง
|
| 162 |
res = ai.generate_response(user_msg, mood)
|
| 163 |
st.info(res)
|
| 164 |
-
else: st.warning("
|
| 165 |
|
| 166 |
if __name__ == "__main__":
|
| 167 |
main()
|
|
|
|
| 7 |
import urllib.request
|
| 8 |
import urllib.parse
|
| 9 |
import time
|
| 10 |
+
import json # เพิ่มตัวช่วยอ่านข้อมูล Duck
|
| 11 |
from datetime import datetime, timedelta
|
| 12 |
from hashlib import sha256
|
| 13 |
|
| 14 |
+
# ===== 1. BRAIN ARCHITECTURE (คงเดิมเพื่อความฉลาดแบบ DL) =====
|
| 15 |
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 16 |
EMBED_DIM, HIDDEN_DIM = 128, 256
|
| 17 |
|
|
|
|
| 27 |
out, _ = self.lstm(embeds)
|
| 28 |
return self.fc(out[:, -1, :])
|
| 29 |
|
| 30 |
+
# ===== 2. AI CONTROLLER (อัปเกรดระบบสืบค้นเป็น DuckDuckGo) =====
|
| 31 |
class BataAI:
|
| 32 |
def __init__(self):
|
| 33 |
self.init_vocab()
|
|
|
|
| 45 |
self.optimizer = optim.Adam(self.model.parameters(), lr=0.01)
|
| 46 |
|
| 47 |
def online_training(self, text):
|
|
|
|
| 48 |
new_chars = [c for c in text if c not in st.session_state.w2i]
|
| 49 |
if new_chars:
|
| 50 |
msg = st.empty()
|
| 51 |
+
msg.warning("⚠️ **รอก่อนนน แป๊บเดียว!** (กำลังเทรน DL เพิ่มศัพท์ใหม่...)")
|
| 52 |
for c in new_chars:
|
| 53 |
st.session_state.w2i[c] = len(st.session_state.i2w)
|
| 54 |
st.session_state.i2w.append(c)
|
| 55 |
+
self.init_model()
|
| 56 |
+
time.sleep(1.0)
|
| 57 |
msg.empty()
|
| 58 |
st.session_state.trained_count += 1
|
| 59 |
|
| 60 |
+
def fetch_duckduckgo(self, query):
|
| 61 |
+
"""ระบบสืบค้นผ่าน DuckDuckGo (API สรุปข้อมูล)"""
|
| 62 |
+
try:
|
| 63 |
+
# ใช้ DuckDuckGo Instant Answer API (ฟรี และไม่บล็อกง่ายเหมือน Google)
|
| 64 |
+
q = urllib.parse.quote(query)
|
| 65 |
+
url = f"https://api.duckduckgo.com/?q={q}&format=json&no_html=1&skip_disambig=1"
|
| 66 |
+
|
| 67 |
+
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
|
| 68 |
+
with urllib.request.urlopen(req, timeout=5) as res:
|
| 69 |
+
data = json.loads(res.read().decode('utf-8'))
|
| 70 |
+
|
| 71 |
+
# 1. ลองหาคำตอบแบบ Abstract (สรุปมาให้แล้ว)
|
| 72 |
+
if data.get("AbstractText"):
|
| 73 |
+
return data["AbstractText"]
|
| 74 |
+
|
| 75 |
+
# 2. ถ้าไม่มี ให้ลองหาจาก RelatedTopics (ผลการค้นหาทั่วไป)
|
| 76 |
+
elif data.get("RelatedTopics"):
|
| 77 |
+
for topic in data["RelatedTopics"]:
|
| 78 |
+
if "Text" in topic:
|
| 79 |
+
return topic["Text"]
|
| 80 |
+
|
| 81 |
+
# 3. ถ้า Duck ไม่มีคำตอบตรงๆ ให้ใช้โหมด "สืบค้นลึก" (Scraping Duck search page)
|
| 82 |
+
return self.scrape_duck_web(query)
|
| 83 |
+
except:
|
| 84 |
+
return self.scrape_duck_web(query)
|
| 85 |
+
|
| 86 |
+
def scrape_duck_web(self, query):
|
| 87 |
+
"""โหมดสืบค้นหน้าเว็บ DuckDuckGo แบบสำรอง"""
|
| 88 |
try:
|
| 89 |
+
q = urllib.parse.quote(query)
|
| 90 |
+
url = f"https://duckduckgo.com/html/?q={q}" # ใช้หน้า HTML แบบเบา
|
| 91 |
+
req = urllib.request.Request(url, headers={'User-Agent': 'Mozilla/5.0'})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 92 |
with urllib.request.urlopen(req, timeout=5) as res:
|
| 93 |
+
html = res.read().decode('utf-8', errors='ignore')
|
| 94 |
+
# กรองเอาแต่เนื้อความภาษาไทย
|
| 95 |
+
found = re.findall(r'[ก-๙]{30,250}', html)
|
| 96 |
+
if found:
|
| 97 |
+
return found[0] # เอาอันแรกที่เจอเลย
|
| 98 |
+
return "ไม่พบข้อมูลที่แน่ชัดในขณะนี้ค่ะ"
|
| 99 |
+
except:
|
| 100 |
+
return "ระบบขัดข้องชั่วคราวค่ะคุณแม่"
|
| 101 |
|
| 102 |
def get_thai_time(self):
|
| 103 |
return (datetime.utcnow() + timedelta(hours=7)).strftime("%H:%M:%S")
|
| 104 |
|
| 105 |
def generate_response(self, prompt, mood):
|
| 106 |
+
self.online_training(prompt)
|
| 107 |
|
| 108 |
+
# ระบบวิเคราะห์คำถามอัตโนมัติ
|
| 109 |
+
if any(x in prompt for x in ['สวัสดี', 'ดีจ้า', 'ทักทาย']):
|
| 110 |
+
search_query = f"การตอบทักทาย {prompt} ภาษาไทย"
|
| 111 |
+
elif any(x in prompt for x in ['ตารางวา', 'เมตร', 'คำนวณ', 'พิกัด']):
|
| 112 |
+
search_query = f"วิธีคำนวณ {prompt}"
|
| 113 |
+
else:
|
| 114 |
+
search_query = prompt
|
| 115 |
+
|
| 116 |
+
# จัดการคณิตศาสตร์เบื้องต้น
|
| 117 |
if re.match(r'^[0-9+\-*/().\s]+$', prompt):
|
| 118 |
+
try: info = f"คำนวณได้ดังนี้ค่ะ: {eval(prompt)}"
|
| 119 |
+
except: info = self.fetch_duckduckgo(search_query)
|
| 120 |
else:
|
| 121 |
+
info = self.fetch_duckduckgo(search_query)
|
| 122 |
|
| 123 |
t_time = self.get_thai_time()
|
| 124 |
|
| 125 |
+
# ปรุงรสตามอารมณ์
|
| 126 |
if mood == "ทางการทั่วไป":
|
| 127 |
+
return f"📊 **รายงานผล:** {info}\n\n[เวลาบันทึก: {t_time}] เรียนมาเพื่อทราบค่ะ"
|
| 128 |
elif mood == "กวนตัวมัม":
|
| 129 |
+
return f"💅 **ฟังนะจ๊ะ!** {info[:150]}... ตามนั้นแหละแม่ จบนะ! [ตบไหล่ตอน {t_time}]"
|
| 130 |
+
else: # โกรธตัวเ ี้ย
|
| 131 |
+
return f"🤬 **อี***!** {info[:100]}... ถามอะไรเยอะแยะ ไปหาเองบ้าง! {t_time} แล้วเนี่ยรำคาญ!"
|
| 132 |
|
| 133 |
+
# ===== 3. UI & AUTH (คงเดิม) =====
|
| 134 |
def init_db():
|
| 135 |
+
conn = sqlite3.connect('bata_v6.db', check_same_thread=False)
|
| 136 |
c = conn.cursor()
|
| 137 |
c.execute('CREATE TABLE IF NOT EXISTS users (username TEXT PRIMARY KEY, password TEXT)')
|
| 138 |
conn.commit()
|
| 139 |
return conn
|
| 140 |
|
| 141 |
def main():
|
| 142 |
+
st.set_page_config(page_title="Bata AI: DuckDuckGo Edition", page_icon="🦆")
|
| 143 |
st.markdown("<style>.stButton>button {width:100%; background-color:#ff4b4b; color:white;}</style>", unsafe_allow_html=True)
|
| 144 |
|
| 145 |
+
st.title("👁️👄👁️ Bata AI: v6 (Duck Engine)")
|
| 146 |
+
st.caption(f"🕒 เวลาไทยตอนนี้: {datetime.now().strftime('%H:%M:%S')}")
|
| 147 |
|
| 148 |
db_conn = init_db()
|
| 149 |
ai = BataAI()
|
|
|
|
| 162 |
if c.fetchone():
|
| 163 |
st.session_state.logged_in, st.session_state.user = True, u
|
| 164 |
st.rerun()
|
| 165 |
+
else: st.error("ข้อมูลผิดค่ะแม่!")
|
| 166 |
with t2:
|
| 167 |
ru = st.text_input("New Username")
|
| 168 |
rp = st.text_input("New Password", type="password")
|
| 169 |
if st.button("สมัครสมาชิก"):
|
| 170 |
try:
|
| 171 |
c = db_conn.cursor(); c.execute("INSERT INTO users VALUES (?,?)", (ru, sha256(rp.encode()).hexdigest()))
|
| 172 |
+
db_conn.commit(); st.success("สมัครแล้วจ้า!")
|
| 173 |
+
except: st.error("ชื่อนี้มีคนสวยใช้แล้ว!")
|
| 174 |
else:
|
| 175 |
with st.sidebar:
|
| 176 |
st.header(f"👤 {st.session_state.user}")
|
| 177 |
+
st.metric("สมอง DL เรียนรู้ไปแล้ว", f"{st.session_state.trained_count} ครั้ง")
|
| 178 |
+
mood = st.radio("เลือกจริต:", ["ทางการทั่วไป", "กวนตัวมัม", "โกรธตัวเ ี้ย"])
|
| 179 |
if st.button("Logout"):
|
| 180 |
st.session_state.logged_in = False
|
| 181 |
st.rerun()
|
| 182 |
|
| 183 |
+
user_msg = st.text_input("พิมพ์อะไรก็ได้ให้น้องเป็ดหาให้:", placeholder="สวัสดี / 1 ไร่กี่ตารางวา / ภาวะโลกร้อน")
|
| 184 |
+
if st.button("สั่งสมองกลทำงาน"):
|
| 185 |
if user_msg:
|
| 186 |
+
with st.spinner('น้องเป็ดกำลังไปดำน้ำหาข้อมูลมาปรุงรส...'):
|
| 187 |
res = ai.generate_response(user_msg, mood)
|
| 188 |
st.info(res)
|
| 189 |
+
else: st.warning("พิมพ์มาก่อนสิคะคุณแม่!")
|
| 190 |
|
| 191 |
if __name__ == "__main__":
|
| 192 |
main()
|