aistv 1.3.4__tar.gz → 1.3.5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aistv
3
- Version: 1.3.4
3
+ Version: 1.3.5
4
4
  Summary: STV AI Chatbot Library for Python
5
5
  Home-page: https://github.com/phuctrong1tuv
6
6
  Author: Trọng Phúc
@@ -0,0 +1,162 @@
1
+ # aistv.py
2
+ import subprocess
3
+ import sys
4
+ import sqlite3
5
+ import time
6
+
7
+ # Tự cài thư viện nếu thiếu
8
+ def install_package(pkg):
9
+ try:
10
+ __import__(pkg)
11
+ except ImportError:
12
+ subprocess.check_call([sys.executable, "-m", "pip", "install", pkg])
13
+
14
+ install_package("groq")
15
+ install_package("requests")
16
+
17
+ from groq import Groq
18
+
19
+ API_KEYS = [
20
+ "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",
21
+ # Thêm key phụ tại đây nếu muốn:
22
+ # "your_second_key",
23
+ ]
24
+
25
+ DB_FILE = "usage.db"
26
+ SPAM_DELAY_SECONDS = 5
27
+
28
+ FREE_MAX_REQUESTS = 20
29
+ NORMAL_MAX_REQUESTS = 30
30
+ VIP_MAX_REQUESTS = None
31
+
32
+ TOKEN_VIP_SET = {
33
+ "aistv",
34
+ "phuc",
35
+ }
36
+
37
+ TOKEN_NORMAL_SET = {
38
+ "tokengsk_...",
39
+ }
40
+
41
+ MODEL_MAP = {
42
+ "Chat-ai-stv-3.5": "meta-llama/llama-3-8b-instruct",
43
+ "Chat-ai-stv-4.0": "meta-llama/llama-3-70b-instruct",
44
+ "Chat-ai-stv-2.3": "meta-llama/llama-4-maverick-17b-128e-instruct",
45
+ "Chat-ai-stv-4.5": "mistralai/mixtral-8x7b-instruct",
46
+ "Chat-ai-stv-5.0": "google/gemma-7b-it",
47
+ }
48
+
49
+ class aistv:
50
+ def __init__(self, token, model, system_prompt=None):
51
+ if token is None:
52
+ raise ValueError("Bạn phải truyền token khi khởi tạo aistv")
53
+ if model is None:
54
+ raise ValueError("Bạn phải truyền model khi khởi tạo aistv")
55
+
56
+ # Bắt buộc model phải nằm trong MODEL_MAP, dùng key nguyên gốc
57
+ if model not in MODEL_MAP:
58
+ raise ValueError(f"Mô hình không hợp lệ: {model}. Dùng: {list(MODEL_MAP.keys())}")
59
+
60
+ self.model_key = model
61
+ self.model = MODEL_MAP[self.model_key]
62
+ self.system_prompt = system_prompt or "Tôi là AI STV, được phát triển bởi Trọng Phúc."
63
+ self.token = token
64
+
65
+ self.api_key_index = 0
66
+ self.client = Groq(api_key=API_KEYS[self.api_key_index])
67
+
68
+ self.history = [{"role": "system", "content": self.system_prompt}]
69
+
70
+ if token in TOKEN_VIP_SET:
71
+ self.max_requests = VIP_MAX_REQUESTS
72
+ self.user_id = token
73
+ elif token in TOKEN_NORMAL_SET:
74
+ self.max_requests = NORMAL_MAX_REQUESTS
75
+ self.user_id = token
76
+ else:
77
+ self.max_requests = FREE_MAX_REQUESTS
78
+ self.user_id = "free_user"
79
+
80
+ self.conn = sqlite3.connect(DB_FILE, check_same_thread=False)
81
+ self.cursor = self.conn.cursor()
82
+ self.cursor.execute('''
83
+ CREATE TABLE IF NOT EXISTS usage (
84
+ user_id TEXT PRIMARY KEY,
85
+ count INTEGER,
86
+ last_time REAL,
87
+ last_date TEXT
88
+ )
89
+ ''')
90
+ self.conn.commit()
91
+ self._init_user()
92
+
93
+ def _init_user(self):
94
+ today = time.strftime("%Y-%m-%d")
95
+ self.cursor.execute("SELECT * FROM usage WHERE user_id = ?", (self.user_id,))
96
+ if not self.cursor.fetchone():
97
+ self.cursor.execute(
98
+ "INSERT INTO usage (user_id, count, last_time, last_date) VALUES (?, ?, ?, ?)",
99
+ (self.user_id, 0, 0, today)
100
+ )
101
+ self.conn.commit()
102
+
103
+ def _get_usage(self):
104
+ self.cursor.execute("SELECT count, last_time, last_date FROM usage WHERE user_id = ?", (self.user_id,))
105
+ row = self.cursor.fetchone()
106
+ return {"count": row[0], "last_time": row[1], "last_date": row[2]} if row else {"count": 0, "last_time": 0, "last_date": time.strftime("%Y-%m-%d")}
107
+
108
+ def _save_usage(self, count, last_time, last_date):
109
+ self.cursor.execute(
110
+ "UPDATE usage SET count = ?, last_time = ?, last_date = ? WHERE user_id = ?",
111
+ (count, last_time, last_date, self.user_id)
112
+ )
113
+ self.conn.commit()
114
+
115
+ def _switch_api_key(self):
116
+ if self.api_key_index + 1 < len(API_KEYS):
117
+ self.api_key_index += 1
118
+ self.client = Groq(api_key=API_KEYS[self.api_key_index])
119
+ return True
120
+ return False
121
+
122
+ def chat(self, prompt: str) -> str:
123
+ usage = self._get_usage()
124
+ now = time.time()
125
+ today = time.strftime("%Y-%m-%d")
126
+
127
+ if usage["last_date"] != today:
128
+ usage["count"] = 0
129
+ usage["last_date"] = today
130
+
131
+ if self.max_requests is not None and usage["count"] >= self.max_requests:
132
+ return f"⚠️ Đã hết {self.max_requests} lượt/ngày. Thử lại mai hoặc xin thêm quyền. https://discord.gg/Ze7RTExgdv"
133
+
134
+ if now - usage["last_time"] < SPAM_DELAY_SECONDS:
135
+ wait_time = SPAM_DELAY_SECONDS - int(now - usage["last_time"])
136
+ return f"⚠️ Vui lòng chờ thêm {wait_time} giây giữa các câu hỏi."
137
+
138
+ self.history.append({"role": "user", "content": prompt})
139
+
140
+ while True:
141
+ try:
142
+ chat_completion = self.client.chat.completions.create(
143
+ messages=self.history,
144
+ model=self.model,
145
+ stream=False,
146
+ )
147
+ reply = chat_completion.choices[0].message.content
148
+ self.history.append({"role": "assistant", "content": reply})
149
+
150
+ if self.max_requests is not None:
151
+ usage["count"] += 1
152
+ usage["last_time"] = now
153
+ self._save_usage(usage["count"], usage["last_time"], usage["last_date"])
154
+
155
+ return reply.strip()
156
+
157
+ except Exception as e:
158
+ if "quota" in str(e).lower() or "token" in str(e).lower():
159
+ if not self._switch_api_key():
160
+ return f"⚠️ API hết hạn hoặc lỗi: {e}"
161
+ else:
162
+ return f"⚠️ Lỗi khi gọi API: {e}"
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: aistv
3
- Version: 1.3.4
3
+ Version: 1.3.5
4
4
  Summary: STV AI Chatbot Library for Python
5
5
  Home-page: https://github.com/phuctrong1tuv
6
6
  Author: Trọng Phúc
@@ -2,7 +2,7 @@ from setuptools import setup, find_packages
2
2
 
3
3
  setup(
4
4
  name="aistv",
5
- version="1.3.4",
5
+ version="1.3.5",
6
6
  description="STV AI Chatbot Library for Python",
7
7
  long_description=open("README.md").read(),
8
8
  long_description_content_type="text/markdown",
aistv-1.3.4/aistv/core.py DELETED
@@ -1,148 +0,0 @@
1
- import subprocess
2
- import sys
3
- import sqlite3
4
- import time
5
-
6
- # Tự cài groq và requests nếu chưa có
7
- def install_package(pkg):
8
- try:
9
- __import__(pkg)
10
- except ImportError:
11
- subprocess.check_call([sys.executable, "-m", "pip", "install", pkg])
12
-
13
- install_package("groq")
14
- install_package("requests")
15
-
16
- import requests
17
- from groq import Groq
18
-
19
- DB_FILE = "usage.db"
20
- SPAM_DELAY_SECONDS = 5
21
-
22
- # Giới hạn theo loại token
23
- FREE_MAX_REQUESTS = 20
24
- NORMAL_MAX_REQUESTS = 30
25
- VIP_MAX_REQUESTS = None # Không giới hạn
26
-
27
- # Ví dụ token thường và token VIP bạn quản lý
28
- TOKEN_VIP_SET = {
29
- "aistv",
30
- "phuc",
31
- }
32
-
33
- TOKEN_NORMAL_SET = {
34
- "aistvgsk_wr9rnhdGCQYCaeAEFQusWGdyb3FYF4LVKrxM0I9JDSGkZIVIymwPgsk_wr9rnhdGCQYCaeAEFQusWGdyb3FYF4LVKrxM0I9JDSGkZIVIymwPgsk_wr9rnhdGCQYCaeAEFQusWGdyb3FYF4LVKrxM0I9JDSGkZIVIymwPgsk_wr9rnhdGCQYCaeAEFQusWGdyb3FYF4LVKrxM0I9JDSGkZIVIymwP",
35
- "tokengsk_wr9rnhdGCQYCaeAEFQusWGdyb3FYF4LVKrxM0I9JDSGkZIVIymwP",
36
- }
37
-
38
- API_KEY = "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"
39
-
40
- class STVBot:
41
- def __init__(self, token: str = None, system_prompt: str = None):
42
- """
43
- token: None (free user), or token string (normal or VIP)
44
- """
45
- if not system_prompt:
46
- system_prompt = "Tôi là AI STV, được phát triển bởi Trọng Phúc."
47
- self.client = Groq(api_key=API_KEY)
48
- self.system_prompt = system_prompt
49
- self.model = "meta-llama/llama-4-maverick-17b-128e-instruct"
50
- self.history = [{"role": "system", "content": self.system_prompt}]
51
-
52
- self.token = token
53
- if token is None:
54
- self.max_requests = FREE_MAX_REQUESTS
55
- self.user_id = "free_user"
56
- elif token in TOKEN_VIP_SET:
57
- self.max_requests = VIP_MAX_REQUESTS
58
- self.user_id = token
59
- elif token in TOKEN_NORMAL_SET:
60
- self.max_requests = NORMAL_MAX_REQUESTS
61
- self.user_id = token
62
- else:
63
- # Token không hợp lệ tính free
64
- self.max_requests = FREE_MAX_REQUESTS
65
- self.user_id = "free_user"
66
-
67
- # Kết nối DB SQLite
68
- self.conn = sqlite3.connect(DB_FILE, check_same_thread=False)
69
- self.cursor = self.conn.cursor()
70
- self.cursor.execute('''
71
- CREATE TABLE IF NOT EXISTS usage (
72
- user_id TEXT PRIMARY KEY,
73
- count INTEGER,
74
- last_time REAL,
75
- last_date TEXT
76
- )
77
- ''')
78
- self.conn.commit()
79
-
80
- # Khởi tạo dữ liệu user nếu chưa có
81
- self._init_user()
82
-
83
- def _init_user(self):
84
- today = time.strftime("%Y-%m-%d")
85
- self.cursor.execute("SELECT * FROM usage WHERE user_id = ?", (self.user_id,))
86
- row = self.cursor.fetchone()
87
- if not row:
88
- self.cursor.execute(
89
- "INSERT INTO usage (user_id, count, last_time, last_date) VALUES (?, ?, ?, ?)",
90
- (self.user_id, 0, 0, today)
91
- )
92
- self.conn.commit()
93
-
94
- def _get_usage(self):
95
- self.cursor.execute("SELECT count, last_time, last_date FROM usage WHERE user_id = ?", (self.user_id,))
96
- row = self.cursor.fetchone()
97
- if row:
98
- return {"count": row[0], "last_time": row[1], "last_date": row[2]}
99
- else:
100
- return {"count": 0, "last_time": 0, "last_date": time.strftime("%Y-%m-%d")}
101
-
102
- def _save_usage(self, count, last_time, last_date):
103
- self.cursor.execute(
104
- "UPDATE usage SET count = ?, last_time = ?, last_date = ? WHERE user_id = ?",
105
- (count, last_time, last_date, self.user_id)
106
- )
107
- self.conn.commit()
108
-
109
- def chat(self, prompt: str) -> str:
110
- usage = self._get_usage()
111
- now = time.time()
112
- today = time.strftime("%Y-%m-%d")
113
-
114
- # Reset count nếu khác ngày
115
- if usage["last_date"] != today:
116
- usage["count"] = 0
117
- usage["last_date"] = today
118
-
119
- if self.max_requests is not None and usage["count"] >= self.max_requests:
120
- return (
121
- f"⚠️ Bạn đã sử dụng hết giới hạn {self.max_requests} câu hỏi trong ngày.\n"
122
- "Vui lòng thử lại vào ngày mai hoặc liên hệ để được cấp thêm quyền.https://discord.gg/Ze7RTExgdv"
123
- )
124
-
125
- if now - usage["last_time"] < SPAM_DELAY_SECONDS:
126
- wait_time = SPAM_DELAY_SECONDS - int(now - usage["last_time"])
127
- return f"⚠️ Vui lòng chờ thêm {wait_time} giây giữa mỗi câu hỏi."
128
-
129
- self.history.append({"role": "user", "content": prompt})
130
-
131
- try:
132
- chat_completion = self.client.chat.completions.create(
133
- messages=self.history,
134
- model=self.model,
135
- stream=False,
136
- )
137
- reply = chat_completion.choices[0].message.content
138
- self.history.append({"role": "assistant", "content": reply})
139
-
140
- if self.max_requests is not None:
141
- usage["count"] += 1
142
- usage["last_time"] = now
143
- self._save_usage(usage["count"], usage["last_time"], usage["last_date"])
144
-
145
- return reply.strip()
146
-
147
- except Exception as e:
148
- return f"⚠️ Lỗi khi gọi API: {e}"
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes