mrbui1990 commited on
Commit
f4d7e6b
·
verified ·
1 Parent(s): 2f32ae1

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +56 -35
app.py CHANGED
@@ -8,63 +8,78 @@ from pathlib import Path
8
 
9
 
10
  MODEL_ID = "bmiller22000/xyntrai-mistral-2.5-7b-chat-nsfw"
11
- MODEL_NAME = "quickmt-en-vi"
12
 
13
 
14
- def translate_text(text,progress=gr.Progress(track_tqdm=True)):
 
 
 
 
 
 
15
  global t
16
 
17
- # 1. Thay đổi thư mục lưu trữ thành một thư mục có quyền ghi (ví dụ: trong thư mục hiện tại /code/ hoặc /app)
18
- # Dùng Path("models") để lưu vào thư mục 'models' trong thư mục hiện tại của ứng dụng (nếu có quyền ghi)
19
- # HOẶC, nếu bạn đang dùng HF Spaces, dùng Path("/tmp") có thể là một giải pháp tốt hơn
20
-
21
- # đây tôi đề xuất dùng thư mục 'models' trong thư mục hiện tại.
22
- # Hãy đảm bảo rằng thư mục này có quyền ghi.
23
 
24
- # Sửa đổi: Sử dụng Path("models") / MODEL_NAME
25
- MODEL_STORAGE_DIR = Path("/tmp")
26
- model_path = MODEL_STORAGE_DIR / MODEL_NAME
27
-
28
- # Đảm bảo thư mục lưu trữ tồn tại trước khi tải
29
- if not MODEL_STORAGE_DIR.exists():
30
- MODEL_STORAGE_DIR.mkdir(parents=True, exist_ok=True)
 
 
 
 
 
 
 
 
31
 
 
32
  if not model_path.exists():
33
- print(f"Downloading model quickmt/{MODEL_NAME} to {model_path}...")
34
  try:
 
35
  hf_download(
36
- model_name="quickmt/" + MODEL_NAME,
37
  output_dir=model_path,
38
  )
 
39
  except Exception as e:
40
- print(f"❌ Lỗi khi tải model: {e}")
41
- # Nếu tải thất bại, trả về văn bản gốc để tránh dừng chương trình
42
- return text
43
 
 
44
  try:
45
- # Giả định biến 't' chưa được định nghĩa hoặc lỗi liên quan đến việc kiểm tra model cũ
46
- # Tôi sẽ đơn giản hóa logic kiểm tra model
47
- global t # Đảm bảo biến t thể được truy cập và sửa đổi.
48
 
49
- # Nếu t chưa được load hoặc đường dẫn model khác
50
- if 't' not in globals() or t is None or str(Path(t.model_path).name) != MODEL_NAME:
51
- print(f"Loading model {MODEL_NAME} from {model_path}")
52
  t = Translator(
53
  str(model_path),
54
- device="auto",
55
  inter_threads=2,
56
  )
57
 
58
  if not text.strip():
59
  return text
60
 
61
- output = t([text], beam_size=1)
 
62
  return output[0]
63
 
64
  except Exception as e:
65
- print(f"❌ Lỗi khi tải hoặc dịch: {e}")
66
- return text
67
-
68
  # Tải model và tokenizer 1 LẦN DUY NHẤT
69
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
70
  model = AutoModelForCausalLM.from_pretrained(
@@ -76,7 +91,7 @@ model = AutoModelForCausalLM.from_pretrained(
76
 
77
  # Thêm một ô system_prompt
78
  @spaces.GPU(duration=60)
79
- def chat_with_model(prompt, system_prompt, chatbot_display, internal_history,progress=gr.Progress(track_tqdm=True)):
80
  """
81
  Hàm này nhận prompt mới, system_prompt, lịch sử hiển thị (của gr.Chatbot)
82
  và lịch sử nội bộ (của gr.State).
@@ -123,7 +138,7 @@ def chat_with_model(prompt, system_prompt, chatbot_display, internal_history,pro
123
 
124
  # 5. Decode *chỉ* phần trả lời mới
125
  response_text = tokenizer.decode(output_tokens[0][inputs.shape[-1]:], skip_special_tokens=True)
126
- translated = translate_text(response_text)
127
  print(response_text)
128
  # 6. Cập nhật "bộ nhớ" (gr.State) với lượt nói MỚI
129
  internal_history.append({"role": "user", "content": prompt})
@@ -160,6 +175,12 @@ with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
160
  placeholder="Nhập tin nhắn của bạn và nhấn Enter...",
161
  lines=1
162
  )
 
 
 
 
 
 
163
 
164
  with gr.Row():
165
  clear_button = gr.Button("Clear Chat")
@@ -180,14 +201,14 @@ with gr.Blocks(theme=gr.themes.Monochrome()) as demo:
180
  prompt_box.submit(
181
  fn=chat_with_model,
182
  inputs=[prompt_box, system_prompt_box, chatbot_display, internal_history],
183
- outputs=[prompt_box, chatbot_display, internal_history]
184
  )
185
 
186
  # Khi người dùng nhấn nút "Send" (ẩn)
187
  submit_button.click(
188
  fn=chat_with_model,
189
  inputs=[prompt_box, system_prompt_box, chatbot_display, internal_history],
190
- outputs=[prompt_box, chatbot_display, internal_history]
191
  )
192
 
193
  # Khi người dùng nhấn nút "Clear Chat"
 
8
 
9
 
10
  MODEL_ID = "bmiller22000/xyntrai-mistral-2.5-7b-chat-nsfw"
 
11
 
12
 
13
+
14
+ # Khởi tạo biến toàn cục t ngoài hàm, như trong code gốc
15
+ t = None
16
+
17
+ # --- Sửa đổi hàm translate_text ---
18
+ # Thêm tham số model_name (mặc định là "quickmt-en-vi")
19
+ def translate_text(text, name=None, progress=gr.Progress(track_tqdm=True)):
20
  global t
21
 
22
+ # 1. Định nghĩa thư mục lưu trữ (Sử dụng 'models' trong thư mục hiện tại)
23
+ model_name = "quickmt-"+name
24
+ MODEL_STORAGE_ROOT = Path("/tmp")
25
+ full_model_name = "quickmt/" + model_name
26
+ model_path = MODEL_STORAGE_ROOT / model_name
 
27
 
28
+ # Đảm bảo thư mục gốc tồn tại
29
+ if not MODEL_STORAGE_ROOT.exists():
30
+ try:
31
+ MODEL_STORAGE_ROOT.mkdir(parents=True, exist_ok=True)
32
+ print(f"Created directory: {MODEL_STORAGE_ROOT}")
33
+ except Exception as e:
34
+ print(f"❌ Cannot create storage directory {MODEL_STORAGE_ROOT}. Error: {e}")
35
+ return text
36
+
37
+ # 2. Kiểm tra sự tồn tại của model trong hf_list()
38
+ # Danh sách các model có sẵn từ quickmt/
39
+ available_models = hf_list()
40
+ if model_name not in available_models:
41
+ print(f"❌ Model '{model_name}' not found in quickmt available list: {available_models}")
42
+ return text # Trả về text gốc nếu model không tồn tại
43
 
44
+ # 3. Tải model nếu chưa có
45
  if not model_path.exists():
46
+ print(f"Downloading model {full_model_name} to {model_path}...")
47
  try:
48
+ # Tải model từ Hugging Face
49
  hf_download(
50
+ model_name=full_model_name,
51
  output_dir=model_path,
52
  )
53
+ print(f"Download complete for {model_name}.")
54
  except Exception as e:
55
+ print(f"❌ Error downloading model {model_name}: {e}")
56
+ return text # Trả về text gốc nếu lỗi tải
 
57
 
58
+ # 4. Load và Dịch
59
  try:
60
+ # Load model nếu đây lần đầu hoặc tên model đã thay đổi
61
+ # Logic này giả định đối tượng t có phương thức .model_path hoặc có thể kiểm tra tên
62
+ is_new_model = (t is None) or (str(Path(t.model_path).name) != model_name)
63
 
64
+ if is_new_model:
65
+ print(f"Loading Translator model: {model_name}")
 
66
  t = Translator(
67
  str(model_path),
68
+ device="auto", # Tự động chọn GPU nếu có
69
  inter_threads=2,
70
  )
71
 
72
  if not text.strip():
73
  return text
74
 
75
+ # Thực hiện dịch
76
+ output = t([text], beam_size=2)
77
  return output[0]
78
 
79
  except Exception as e:
80
+ print(f"❌ Error during model loading or translation for {model_name}: {e}")
81
+ return text # Trả về text gốc nếu có lỗi trong quá trình load/dịch
82
+
83
  # Tải model và tokenizer 1 LẦN DUY NHẤT
84
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
85
  model = AutoModelForCausalLM.from_pretrained(
 
91
 
92
  # Thêm một ô system_prompt
93
  @spaces.GPU(duration=60)
94
+ def chat_with_model(prompt, system_prompt, chatbot_display, internal_history,lang,progress=gr.Progress(track_tqdm=True)):
95
  """
96
  Hàm này nhận prompt mới, system_prompt, lịch sử hiển thị (của gr.Chatbot)
97
  và lịch sử nội bộ (của gr.State).
 
138
 
139
  # 5. Decode *chỉ* phần trả lời mới
140
  response_text = tokenizer.decode(output_tokens[0][inputs.shape[-1]:], skip_special_tokens=True)
141
+ translated = translate_text(response_text,lang)
142
  print(response_text)
143
  # 6. Cập nhật "bộ nhớ" (gr.State) với lượt nói MỚI
144
  internal_history.append({"role": "user", "content": prompt})
 
175
  placeholder="Nhập tin nhắn của bạn và nhấn Enter...",
176
  lines=1
177
  )
178
+
179
+ lang = gr.Textbox(
180
+ label="lang",
181
+ placeholder="...",
182
+ lines=1
183
+ )
184
 
185
  with gr.Row():
186
  clear_button = gr.Button("Clear Chat")
 
201
  prompt_box.submit(
202
  fn=chat_with_model,
203
  inputs=[prompt_box, system_prompt_box, chatbot_display, internal_history],
204
+ outputs=[prompt_box, chatbot_display, internal_history,lang]
205
  )
206
 
207
  # Khi người dùng nhấn nút "Send" (ẩn)
208
  submit_button.click(
209
  fn=chat_with_model,
210
  inputs=[prompt_box, system_prompt_box, chatbot_display, internal_history],
211
+ outputs=[prompt_box, chatbot_display, internal_history,lang]
212
  )
213
 
214
  # Khi người dùng nhấn nút "Clear Chat"