MINZO4546 commited on
Commit
c38e36c
·
verified ·
1 Parent(s): 7a03f1b

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +29 -72
app.py CHANGED
@@ -3,12 +3,9 @@ from fastapi.middleware.cors import CORSMiddleware
3
  from pydantic import BaseModel
4
  import torch
5
  import os
6
- import json
7
  import re
8
- import uuid
9
  import secrets
10
- import datetime
11
- from transformers import AutoModelForCausalLM, AutoTokenizer
12
  from duckduckgo_search import DDGS
13
 
14
  app = FastAPI()
@@ -20,100 +17,60 @@ app.add_middleware(
20
  allow_headers=["*"],
21
  )
22
 
23
- # --- Database & Config ---
24
- # ආරම්භක Keys
25
  API_KEYS_DB = {
26
- "ELE-PRIME-ADMIN-SYS": {"limit": 10000, "used": 0, "status": "active"},
27
- "ELE-PRIME-YG5EPZFQ": {"limit": 5000, "used": 0, "status": "active"}
28
  }
29
  ADMIN_SECRET = "MINZO-SECRET-2026"
30
 
31
- # --- AI Model ---
32
- model_id = "google/gemma-3-1b-it"
33
- print(f"🔱 INACHI-CORE: Loading {model_id}...")
 
 
 
 
 
 
34
 
35
  tokenizer = AutoTokenizer.from_pretrained(model_id)
36
- model = AutoModelForCausalLM.from_pretrained(model_id, torch_dtype="auto", device_map="cpu")
 
 
 
 
37
 
38
- # --- Data Models ---
39
  class AdminRequest(BaseModel):
40
  admin_pass: str
41
- limit: int = 1000
42
-
43
- # --- API Endpoints ---
44
-
45
- @app.get("/")
46
- def home():
47
- return {"status": "Elephant Pro Active", "active_keys": len(API_KEYS_DB)}
48
-
49
- # 🔱 අලුතින් Key එකක් Auto-Generate කරන Endpoint එක
50
- @app.post("/v1/generate-key")
51
- async def generate_key(data: AdminRequest):
52
- if data.admin_pass != ADMIN_SECRET:
53
- raise HTTPException(status_code=401, detail="Unauthorized Specialist Access!")
54
-
55
- # Random Key එකක් නිර්මාණය කිරීම (උදා: ELE-PRIME-X8A2...)
56
- new_key = f"ELE-PRIME-{secrets.token_hex(4).upper()}"
57
- API_KEYS_DB[new_key] = {"limit": data.limit, "used": 0, "status": "active"}
58
-
59
- return {
60
- "message": "New Specialist Key Activated",
61
- "api_key": new_key,
62
- "limit": data.limit
63
- }
64
 
65
  @app.post("/v1/chat")
66
  async def chat(message: dict, x_api_key: str = Header(None)):
67
  if not x_api_key or x_api_key not in API_KEYS_DB:
68
- raise HTTPException(status_code=403, detail="Access Denied")
69
 
70
- key_info = API_KEYS_DB[x_api_key]
71
- if key_info["used"] >= key_info["limit"]:
72
- raise HTTPException(status_code=429, detail="Limit Reached")
73
-
74
  query = message.get("query", "")
75
-
76
- # Web Search
77
- context = ""
78
- if any(w in query.lower() for w in ["today", "now", "2026", "අද"]):
79
- try:
80
- with DDGS() as ddgs:
81
- results = list(ddgs.text(query, max_results=2))
82
- context = "\n".join([r['body'] for r in results])
83
- except: pass
84
-
85
- # 🔱 Language Adaptive System Instruction
86
  system_instruction = (
87
- "You are Elephant AI (Inachi-Core), an expert assistant for Specialist MINZO-PRIME. "
88
- "Respond in the language used by the user (Sinhala or English). "
89
- f"Real-time Context: {context}"
90
  )
91
 
92
- msgs = [
93
- {"role": "system", "content": system_instruction},
94
- {"role": "user", "content": query}
95
- ]
96
-
97
- text = tokenizer.apply_chat_template(msgs, tokenize=False, add_generation_prompt=True)
98
- inputs = tokenizer([text], return_tensors="pt").to("cpu")
99
 
100
  with torch.no_grad():
101
  outputs = model.generate(
102
- inputs.input_ids,
103
  max_new_tokens=512,
104
- temperature=0.6,
105
- top_p=0.9,
106
  do_sample=True,
107
  pad_token_id=tokenizer.eos_token_id
108
  )
109
 
110
- full_response = tokenizer.batch_decode(outputs, skip_special_tokens=True)[0]
111
- ans = full_response.split("assistant")[-1].strip()
112
-
113
- # Cleaning Logic
114
- if "</think>" in ans: ans = ans.split("</think>")[-1].strip()
115
- ans = ans.replace("Ċ", "\n").replace("Ġ", " ")
116
- ans = re.sub(r' +', ' ', ans).strip()
117
 
118
  API_KEYS_DB[x_api_key]["used"] += 1
119
  return {"reply": ans, "usage": API_KEYS_DB[x_api_key]["used"]}
 
3
  from pydantic import BaseModel
4
  import torch
5
  import os
 
6
  import re
 
7
  import secrets
8
+ from transformers import AutoModelForCausalLM, AutoTokenizer, BitsAndBytesConfig
 
9
  from duckduckgo_search import DDGS
10
 
11
  app = FastAPI()
 
17
  allow_headers=["*"],
18
  )
19
 
20
+ # --- Specialist DB ---
 
21
  API_KEYS_DB = {
22
+ "ELE-PRIME-ADMIN-SYS": {"limit": 100000, "used": 0, "status": "active"},
23
+ "ELE-PRIME-VOID-X": {"limit": 50000, "used": 0, "status": "active"}
24
  }
25
  ADMIN_SECRET = "MINZO-SECRET-2026"
26
 
27
+ # --- MiMo-Audio 7B Optimization ---
28
+ model_id = "XiaomiMiMo/MiMo-Audio-7B-Instruct"
29
+ print(f"🔱 INACHI-CORE: Deploying Multimodal Engine {model_id}...")
30
+
31
+ # 4-bit Quantization එකතු කිරීම (CPU/RAM ඉතිරි කිරීමට)
32
+ quant_config = BitsAndBytesConfig(
33
+ load_in_4bit=True,
34
+ bnb_4bit_compute_dtype=torch.float16
35
+ )
36
 
37
  tokenizer = AutoTokenizer.from_pretrained(model_id)
38
+ model = AutoModelForCausalLM.from_pretrained(
39
+ model_id,
40
+ quantization_config=quant_config,
41
+ device_map="auto" # මෙය ස්වයංක්‍රීයව RAM එක කළමනාකරණය කරයි
42
+ )
43
 
 
44
  class AdminRequest(BaseModel):
45
  admin_pass: str
46
+ limit: int = 5000
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
47
 
48
  @app.post("/v1/chat")
49
  async def chat(message: dict, x_api_key: str = Header(None)):
50
  if not x_api_key or x_api_key not in API_KEYS_DB:
51
+ raise HTTPException(status_code=403, detail="Invalid Key")
52
 
 
 
 
 
53
  query = message.get("query", "")
54
+
55
+ # MiMo පද්ධතියේ System Prompt එක
 
 
 
 
 
 
 
 
 
56
  system_instruction = (
57
+ "You are Inachi-Prime, an Any-to-Any multimodal AI assistant. "
58
+ "You are designed by Specialist MINZO-PRIME. "
59
+ "Respond accurately in Sinhala or English based on user input."
60
  )
61
 
62
+ inputs = tokenizer(f"{system_instruction}\n\nUser: {query}\nAssistant:", return_tensors="pt").to("cpu")
 
 
 
 
 
 
63
 
64
  with torch.no_grad():
65
  outputs = model.generate(
66
+ **inputs,
67
  max_new_tokens=512,
68
+ temperature=0.7,
 
69
  do_sample=True,
70
  pad_token_id=tokenizer.eos_token_id
71
  )
72
 
73
+ ans = tokenizer.decode(outputs[0], skip_special_tokens=True).split("Assistant:")[-1].strip()
 
 
 
 
 
 
74
 
75
  API_KEYS_DB[x_api_key]["used"] += 1
76
  return {"reply": ans, "usage": API_KEYS_DB[x_api_key]["used"]}