Update app.py
Browse files
app.py
CHANGED
|
@@ -7,11 +7,11 @@ import re
|
|
| 7 |
import urllib.request
|
| 8 |
import urllib.parse
|
| 9 |
import time
|
| 10 |
-
import json
|
| 11 |
from datetime import datetime, timedelta
|
| 12 |
from hashlib import sha256
|
| 13 |
|
| 14 |
-
# ===== 1. BRAIN ARCHITECTURE (
|
| 15 |
DEVICE = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 16 |
EMBED_DIM, HIDDEN_DIM = 128, 256
|
| 17 |
|
|
@@ -27,7 +27,7 @@ class BataLanguageModel(nn.Module):
|
|
| 27 |
out, _ = self.lstm(embeds)
|
| 28 |
return self.fc(out[:, -1, :])
|
| 29 |
|
| 30 |
-
# ===== 2. AI CONTROLLER (
|
| 31 |
class BataAI:
|
| 32 |
def __init__(self):
|
| 33 |
self.init_vocab()
|
|
@@ -48,56 +48,39 @@ class BataAI:
|
|
| 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 |
try:
|
| 63 |
-
# ใ
|
| 64 |
-
|
| 65 |
-
url = f"https://api.duckduckgo.com/?q={
|
| 66 |
|
| 67 |
-
req = urllib.request.Request(url, headers={'User-Agent': '
|
| 68 |
with urllib.request.urlopen(req, timeout=5) as res:
|
| 69 |
data = json.loads(res.read().decode('utf-8'))
|
| 70 |
|
| 71 |
-
# 1. ลอง
|
| 72 |
if data.get("AbstractText"):
|
| 73 |
return data["AbstractText"]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 74 |
|
| 75 |
-
|
| 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
|
| 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")
|
|
@@ -105,32 +88,24 @@ class BataAI:
|
|
| 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"คำนวณ
|
| 119 |
-
except: info = self.
|
| 120 |
else:
|
| 121 |
-
info = self.
|
| 122 |
|
| 123 |
t_time = self.get_thai_time()
|
| 124 |
|
| 125 |
-
# ปรุง
|
| 126 |
if mood == "ทางการทั่วไป":
|
| 127 |
-
return f"📊 **รายงานผล:** {info}\n\n[
|
| 128 |
elif mood == "กวนตัวมัม":
|
| 129 |
-
return f"💅 **ฟังนะจ๊ะ!** {info[:150]}... ตาม
|
| 130 |
-
else: # โกรธตัวเ
|
| 131 |
-
return f"🤬 **อี***!** {info[:100]}... ถามอ
|
| 132 |
|
| 133 |
-
# ===== 3.
|
| 134 |
def init_db():
|
| 135 |
conn = sqlite3.connect('bata_v6.db', check_same_thread=False)
|
| 136 |
c = conn.cursor()
|
|
@@ -138,12 +113,13 @@ def init_db():
|
|
| 138 |
conn.commit()
|
| 139 |
return conn
|
| 140 |
|
|
|
|
| 141 |
def main():
|
| 142 |
-
st.set_page_config(page_title="Bata AI:
|
| 143 |
-
st.markdown("<style>.stButton>button {width:100%; background-color:#ff4b4b; color:white;}</style>", unsafe_allow_html=True)
|
| 144 |
|
| 145 |
-
st.title("👁️👄👁️ Bata AI:
|
| 146 |
-
st.caption(f"🕒 เวลาไทย
|
| 147 |
|
| 148 |
db_conn = init_db()
|
| 149 |
ai = BataAI()
|
|
@@ -153,8 +129,8 @@ def main():
|
|
| 153 |
if not st.session_state.logged_in:
|
| 154 |
t1, t2 = st.tabs(["Login", "Register"])
|
| 155 |
with t1:
|
| 156 |
-
u = st.text_input("
|
| 157 |
-
p = st.text_input("
|
| 158 |
if st.button("เข้าสู่ระบบ"):
|
| 159 |
hp = sha256(p.encode()).hexdigest()
|
| 160 |
c = db_conn.cursor()
|
|
@@ -162,31 +138,23 @@ def main():
|
|
| 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("
|
| 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("
|
| 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()
|
|
|
|
| 7 |
import urllib.request
|
| 8 |
import urllib.parse
|
| 9 |
import time
|
| 10 |
+
import json
|
| 11 |
from datetime import datetime, timedelta
|
| 12 |
from hashlib import sha256
|
| 13 |
|
| 14 |
+
# ===== 1. BRAIN ARCHITECTURE (LSTM Language Model) =====
|
| 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 Engine) =====
|
| 31 |
class BataAI:
|
| 32 |
def __init__(self):
|
| 33 |
self.init_vocab()
|
|
|
|
| 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("⚠️ **รอก่อนนน แป๊บเดียว!** (กำลัง Sync ข้อมูลเข้าสมองกล...)")
|
| 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 fetch_duck_info(self, query):
|
| 61 |
+
"""ดึงข้อมูลจาก DuckDuckGo API (ตอบคำถาม/คำนวณ/ทักทาย)"""
|
| 62 |
try:
|
| 63 |
+
# ปรับแต่ง Query ให้ DuckDuckGo เข้าใจง่ายๆ
|
| 64 |
+
search_query = f"answer for {query}" if len(query) < 10 else query
|
| 65 |
+
url = f"https://api.duckduckgo.com/?q={urllib.parse.quote(search_query)}&format=json&no_html=1&skip_disambig=1"
|
| 66 |
|
| 67 |
+
req = urllib.request.Request(url, headers={'User-Agent': 'BataAI-V6-Agent'})
|
| 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 |
+
# 2. ถ้าเป็นคำนวณหรือคำสั้นๆ ลองดึง Answer
|
| 75 |
+
elif data.get("Answer"):
|
| 76 |
+
return data["Answer"]
|
| 77 |
+
# 3. ถ้าไม่มีจริงๆ ให้ลองดึงประโยคแรกของผลลัพธ์ที่เกี่ยวข้อง
|
| 78 |
+
elif data.get("RelatedTopics") and len(data["RelatedTopics"]) > 0:
|
| 79 |
+
return data["RelatedTopics"][0].get("Text", "พบข้อมูลที่เกี่ยวข้องแต่ยังระบุรายละเอียดไม่ได้ค่ะ")
|
| 80 |
|
| 81 |
+
return f"ขออภัยค่ะ ข้อมูลเกี่ยวกับ '{query}' ยังไม่ถูกบรรจุในระบบ แต่ดิฉันได้บันทึกไว้เทรนต่อแล้วค่ะ"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
except:
|
| 83 |
+
return "ดูเหมือนสัญญาณดาวเทียม DuckDuckGo จะขัดข้องค่ะแม่!"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
|
| 85 |
def get_thai_time(self):
|
| 86 |
return (datetime.utcnow() + timedelta(hours=7)).strftime("%H:%M:%S")
|
|
|
|
| 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"จากการคำนวณระดับควอนตัม ผลลัพธ์คือ {eval(prompt)}"
|
| 94 |
+
except: info = self.fetch_duck_info(prompt)
|
| 95 |
else:
|
| 96 |
+
info = self.fetch_duck_info(prompt)
|
| 97 |
|
| 98 |
t_time = self.get_thai_time()
|
| 99 |
|
| 100 |
+
# ปรุงแต่งตามจริตที่เลือก
|
| 101 |
if mood == "ทางการทั่วไป":
|
| 102 |
+
return f"📊 **รายงานผล:** {info}\n\n[Thai Time: {t_time}] หวังว่าข้อมูลนี้จะเป็นประโยชน์ต่อการตัดสินใจค่ะ"
|
| 103 |
elif mood == "กวนตัวมัม":
|
| 104 |
+
return f"💅 **ฟังนะจ๊ะ!** {info[:150]}... จบป่ะ? ไม่ต้องถามซ้ำนะ ป้าจะไปจองคิวทำเล็บแล้ว! [{t_time}]"
|
| 105 |
+
else: # โกรธตัวเ-ี้ย
|
| 106 |
+
return f"🤬 **อี***!** {info[:100]}... ถามอยู่ได้! {t_time} แล้วเนี่ย หูตาหัดหาเองบ้างสิคะ เสียเวลาตัวแม่จริงๆ!"
|
| 107 |
|
| 108 |
+
# ===== 3. DATABASE & AUTH =====
|
| 109 |
def init_db():
|
| 110 |
conn = sqlite3.connect('bata_v6.db', check_same_thread=False)
|
| 111 |
c = conn.cursor()
|
|
|
|
| 113 |
conn.commit()
|
| 114 |
return conn
|
| 115 |
|
| 116 |
+
# ===== 4. UI (Bata AI v6) =====
|
| 117 |
def main():
|
| 118 |
+
st.set_page_config(page_title="Bata AI: Duck Engine v6", page_icon="🦆")
|
| 119 |
+
st.markdown("<style>.stButton>button {width:100%; background-color:#ff4b4b; color:white; border-radius:15px;}</style>", unsafe_allow_html=True)
|
| 120 |
|
| 121 |
+
st.title("👁️👄👁️ Bata AI: Duck Engine v6")
|
| 122 |
+
st.caption(f"🕒 รายงานเวลาประเทศไทย: {datetime.now().strftime('%H:%M:%S')}")
|
| 123 |
|
| 124 |
db_conn = init_db()
|
| 125 |
ai = BataAI()
|
|
|
|
| 129 |
if not st.session_state.logged_in:
|
| 130 |
t1, t2 = st.tabs(["Login", "Register"])
|
| 131 |
with t1:
|
| 132 |
+
u = st.text_input("ชื่อผู้ใช้")
|
| 133 |
+
p = st.text_input("รหัสผ่าน", type="password")
|
| 134 |
if st.button("เข้าสู่ระบบ"):
|
| 135 |
hp = sha256(p.encode()).hexdigest()
|
| 136 |
c = db_conn.cursor()
|
|
|
|
| 138 |
if c.fetchone():
|
| 139 |
st.session_state.logged_in, st.session_state.user = True, u
|
| 140 |
st.rerun()
|
| 141 |
+
else: st.error("รหัสผิดค่ะคุณแม่!")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 142 |
else:
|
| 143 |
with st.sidebar:
|
| 144 |
st.header(f"👤 {st.session_state.user}")
|
| 145 |
+
st.metric("DL Knowledge Level", f"{st.session_state.trained_count}")
|
| 146 |
+
mood = st.radio("เลือกจริตตัวแม่:", ["ทางการทั่วไป", "กวนตัวมัม", "โกรธตัวเ ี้ย"])
|
| 147 |
if st.button("Logout"):
|
| 148 |
st.session_state.logged_in = False
|
| 149 |
st.rerun()
|
| 150 |
|
| 151 |
+
user_msg = st.text_input("คุยกับสมองกล Bata AI:", placeholder="ถามคำนวณ, ทักทาย หรือเรื่องที่อยากรู้...")
|
| 152 |
+
if st.button("ประมวลผล (Duck Engine)"):
|
| 153 |
if user_msg:
|
| 154 |
+
with st.spinner('กำลังถามเป็ด (DuckDuckGo) และเทรน LSTM...'):
|
| 155 |
res = ai.generate_response(user_msg, mood)
|
| 156 |
st.info(res)
|
| 157 |
+
else: st.warning("พิมพ์อะไรมาหน่อยสิคะแม่!")
|
| 158 |
|
| 159 |
if __name__ == "__main__":
|
| 160 |
main()
|