1234ty commited on
Commit
4e1d2cf
·
verified ·
1 Parent(s): df7fbc9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +63 -57
app.py CHANGED
@@ -1,57 +1,63 @@
1
- from fastapi import FastAPI, HTTPException
2
- from fastapi.middleware.cors import CORSMiddleware
3
- from pydantic import BaseModel
4
- import torch
5
- from diffusers import FluxPipeline
6
- import base64
7
- from io import BytesIO
8
-
9
- app = FastAPI()
10
-
11
- # ปลดล็อก CORS ให้หน้็บรียกใช้ได้
12
- app.add_middleware(
13
- CORSMiddleware,
14
- allow_origins=["*"],
15
- allow_methods=["*"],
16
- allow_headers=["*"],
17
- )
18
-
19
- # ใชโมเดล FLUX.1 [schnell] ที่ขึ้นชื่อว่เร็วและสวยที่สดในตอนนี
20
- model_id = "black-forest-labs/FLUX.1-schnell"
21
-
22
- device = "cuda" if torch.cuda.is_available() else "cpu"
23
- # FLUX กินสเปกหน่อย แต่ถ้าใช้ bfloat16 จะรันได้เสถียรขึ้น
24
- torch_dtype = torch.bfloat16 if torch.cuda.is_available() else torch.float32
25
-
26
- print(f"กำลังปลุกวิญญาณ FLUX บน: {device}...")
27
- # โหลดแบบลดสเปกเพื่อให้รันบน Space ฟรีได้ (offload ถ้าจำเป็น)
28
- pipe = FluxPipeline.from_pretrained(model_id, torch_dtype=torch_dtype)
29
- pipe.to(device)
30
- print("FLUX ้อมแผลงฤทธ์แล้วเสี่ย!")
31
-
32
- class PromptRequest(BaseModel):
33
- prompt: str
34
-
35
- @app.post("/generate")
36
- async def generate(request: PromptRequest):
37
- try:
38
- # FLUX [schnell] ใช้แค่ 2-4 step ก็สวยแล้ว (ประหยัดเวลามาก)
39
- image = pipe(
40
- request.prompt,
41
- guidance_scale=0.0,
42
- num_inference_steps=4,
43
- max_sequence_length=256
44
- ).images[0]
45
-
46
- buffered = BytesIO()
47
- image.save(buffered, format="PNG")
48
- img_str = base64.b64encode(buffered.getvalue()).decode()
49
-
50
- return {"image": f"data:image/png;base64,{img_str}"}
51
- except Exception as e:
52
- print(f"พังครับเสี่ย: {e}")
53
- raise HTTPException(status_code=500, detail=str(e))
54
-
55
- if __name__ == "__main__":
56
- import uvicorn
57
- uvicorn.run(app, host="0.0.0.0", port=7860)
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from llama_cpp import Llama
3
+ from huggingface_hub import hf_hub_download
4
+ import os
5
+
6
+ # --- 1. การตั้งค่าโมเดล (The Sandbox Model) ---
7
+ # เลือกโมเดลที่เก่งภาษาไทยและขนาดไม่เกิน RAM ฟรีของ HF
8
+ repo_id = "QuantFactory/Llama-3-8B-Instruct-GGUF"
9
+ filename = "Llama-3-8B-Instruct.Q4_K_M.gguf"
10
+
11
+ print("กำังดาวน์โหลดโมเดลเขาสู่ Sandbox... โปรดรอสักครู่")
12
+ model_path = hf_hub_download(repo_id=repo_id, filename=filename)
13
+
14
+ # โหลดโมเดลเข้าสู่ Memory
15
+ # n_ctx คือจำนวนคำที่จำได้ (ปรับตามความแรงเครื่อง)
16
+ llm = Llama(model_path=model_path, n_ctx=2048, n_threads=2)
17
+
18
+ # --- 2. ขอบเขตคำสั่ง (System Prompt) ---
19
+ SYSTEM_PROMPT = "คุณคือผูช่วย AI ที่ฉลและสุภาพ ตอบเป็ภาษาไทยอย่างถูกตอง อยู่ในกรอบของระบบปิด"
20
+
21
+ def respond(message, history):
22
+ # รวมประวัติการแชทเพื่อให้ AI จำบริบทได้
23
+ prompt = f"<|begin_of_text|><|start_header_id|>system<|end_header_id|>\n\n{SYSTEM_PROMPT}<|eot_id|>"
24
+
25
+ for user_msg, bot_msg in history:
26
+ prompt += f"<|start_header_id|>user<|end_header_id|>\n\n{user_msg}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n{bot_msg}<|eot_id|>"
27
+
28
+ prompt += f"<|start_header_id|>user<|end_header_id|>\n\n{message}<|eot_id|><|start_header_id|>assistant<|end_header_id|>\n\n"
29
+
30
+ #ัน AI ในก่อด (Local Inference)
31
+ output = llm(
32
+ prompt,
33
+ max_tokens=512,
34
+ stop=["<|eot_id|>"],
35
+ echo=False
36
+ )
37
+
38
+ return output["choices"][0]["text"].strip()
39
+
40
+ # --- 3. สร้าง UI หน้าแชท ---
41
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
42
+ gr.Markdown("# 🤖 My Local AI Sandbox (Thai Edition)")
43
+ gr.Markdown("โมเดลนี้รันอยู่บน CPU ของ Hugging Face โดยตรง ไม่มีการส่งข้อมูลไปข้างนอก")
44
+
45
+ chatbot = gr.Chatbot(label="ห้องแชทส่วนตัว")
46
+ msg = gr.Textbox(label="พิมพ์คำถามของคุณที่นี่", placeholder="สวัสดีครับ...")
47
+ clear = gr.Button("ล้างการสนทนา")
48
+
49
+ def user(user_message, history):
50
+ return "", history + [[user_message, None]]
51
+
52
+ def bot(history):
53
+ user_message = history[-1][0]
54
+ bot_message = respond(user_message, history[:-1])
55
+ history[-1][1] = bot_message
56
+ return history
57
+
58
+ msg.submit(user, [msg, chatbot], [msg, chatbot], queue=False).then(
59
+ bot, chatbot, chatbot
60
+ )
61
+ clear.click(lambda: None, None, chatbot, queue=False)
62
+
63
+ demo.launch()