mrbui1990 commited on
Commit
a2d9815
·
verified ·
1 Parent(s): dd7ccad

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +57 -60
app.py CHANGED
@@ -35,75 +35,70 @@ def preload_quickmt_models():
35
  preload_quickmt_models()
36
 
37
  MODEL_ID = "bmiller22000/xyntrai-mistral-2.5-7b-chat-nsfw"
38
-
39
 
40
 
41
  # Khởi tạo biến toàn cục t ngoài hàm, như trong code gốc
42
  t = None
43
 
 
 
 
 
 
 
 
 
 
 
44
  # --- Sửa đổi hàm translate_text ---
45
  # Thêm tham số model_name (mặc định là "quickmt-en-vi")
46
- def translate_text(text, name=None, progress=gr.Progress(track_tqdm=True)):
47
- global t
 
 
 
 
 
 
 
 
 
 
48
 
49
- # 1. Định nghĩa thư mục lưu trữ (Sử dụng 'models' trong thư mục hiện tại)
50
- model_name = "quickmt-"+name
51
- MODEL_STORAGE_ROOT = Path("/home/user/data")
52
- full_model_name = "quickmt/" + model_name
53
- model_path = MODEL_STORAGE_ROOT / model_name
 
54
 
55
- # Đảm bảo thư mục gốc tồn tại
56
- if not MODEL_STORAGE_ROOT.exists():
57
- try:
58
- MODEL_STORAGE_ROOT.mkdir(parents=True, exist_ok=True)
59
- print(f"Created directory: {MODEL_STORAGE_ROOT}")
60
- except Exception as e:
61
- print(f"❌ Cannot create storage directory {MODEL_STORAGE_ROOT}. Error: {e}")
62
- return text
63
-
64
- # 2. Kiểm tra sự tồn tại của model trong hf_list()
65
- # Danh sách các model có sẵn từ quickmt/
66
- available_models = hf_list()
67
- if full_model_name not in available_models:
68
- print(f"❌ Model '{full_model_name}' not found in quickmt available list: {available_models}")
69
- return text # Trả về text gốc nếu model không tồn tại
70
-
71
- # 3. Tải model nếu chưa có
72
- if not model_path.exists():
73
- print(f"Downloading model {full_model_name} to {model_path}...")
74
- try:
75
- # Tải model từ Hugging Face
76
- hf_download(
77
- model_name=full_model_name,
78
- output_dir=model_path,
79
- )
80
- print(f"Download complete for {model_name}.")
81
- except Exception as e:
82
- print(f"❌ Error downloading model {model_name}: {e}")
83
- return text # Trả về text gốc nếu lỗi tải
84
-
85
- # 4. Load và Dịch
86
- try:
87
- # Load model nếu đây là lần đầu hoặc tên model đã thay đổi
88
- # 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
89
- is_new_model = (t is None) or (str(Path(t.model_path).name) != model_name)
90
-
91
- if is_new_model:
92
- print(f"Loading Translator model: {model_name}")
93
- t = Translator(
94
- str(model_path),
95
- device="auto", # Tự động chọn GPU nếu có
96
- inter_threads=2,
97
- )
98
-
99
- print(f"Translate....")
100
- # Thực hiện dịch
101
- output = t([text], beam_size=2)
102
- return output[0]
103
-
104
- except Exception as e:
105
- print(f"❌ Error during model loading or translation for {model_name}: {e}")
106
- return text # Trả về text gốc nếu có lỗi trong quá trình load/dịch
107
 
108
  # Tải model và tokenizer 1 LẦN DUY NHẤT
109
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
@@ -114,6 +109,8 @@ model = AutoModelForCausalLM.from_pretrained(
114
  trust_remote_code=True
115
  )
116
 
 
 
117
  # Thêm một ô system_prompt
118
  @spaces.GPU(duration=60)
119
  def chat_with_model(prompt, system_prompt, chatbot_display, internal_history,lang,gender,progress=gr.Progress(track_tqdm=True)):
 
35
  preload_quickmt_models()
36
 
37
  MODEL_ID = "bmiller22000/xyntrai-mistral-2.5-7b-chat-nsfw"
38
+ # Load model and tokenizer
39
 
40
 
41
  # Khởi tạo biến toàn cục t ngoài hàm, như trong code gốc
42
  t = None
43
 
44
+ model_name_or_path = "tencent/Hunyuan-MT-7B"
45
+ print("Loading model... This may take a few minutes.")
46
+
47
+ tokenizer_trans = AutoTokenizer.from_pretrained(model_name_or_path)
48
+ model_trans = AutoModelForCausalLM.from_pretrained(
49
+ model_name_or_path,
50
+ torch_dtype=torch.bfloat16,
51
+ device_map="auto"
52
+ )
53
+
54
  # --- Sửa đổi hàm translate_text ---
55
  # Thêm tham số model_name (mặc định là "quickmt-en-vi")
56
+ def translate_text(text, lang=None, progress=gr.Progress(track_tqdm=True)):
57
+ # Set default values if None (happens during example caching)
58
+ if lang is None:
59
+ return text
60
+ if system_message is None:
61
+ system_message = "You are a helpful AI assistant."
62
+ if max_tokens is None:
63
+ max_tokens = 512
64
+ if temperature is None:
65
+ temperature = 0.7
66
+ if top_p is None:
67
+ top_p = 0.95
68
 
69
+ # Build conversation history
70
+ messages = []
71
+ message = "Translate to "+lang+": "+text
72
+ # Add system message if provided
73
+ if system_message:
74
+ messages.append({"role": "system", "content": system_message})
75
 
76
+ # Add current message
77
+ messages.append({"role": "user", "content": message})
78
+
79
+ # Tokenize the conversation
80
+ tokenized_chat = tokenizer_trans.apply_chat_template(
81
+ messages,
82
+ tokenize=True,
83
+ add_generation_prompt=True,
84
+ return_tensors="pt"
85
+ )
86
+
87
+ # Generate response
88
+ with torch.no_grad():
89
+ outputs = model_trans.generate(
90
+ tokenized_chat.to(model.device),
91
+ max_new_tokens=max_tokens,
92
+ temperature=temperature,
93
+ top_p=top_p,
94
+ do_sample=True if temperature > 0 else False,
95
+ pad_token_id=tokenizer.eos_token_id
96
+ )
97
+
98
+ # Decode only the new tokens
99
+ response = tokenizer.decode(outputs[0][tokenized_chat.shape[-1]:], skip_special_tokens=True)
100
+
101
+ return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
  # Tải model và tokenizer 1 LẦN DUY NHẤT
104
  tokenizer = AutoTokenizer.from_pretrained(MODEL_ID, trust_remote_code=True)
 
109
  trust_remote_code=True
110
  )
111
 
112
+
113
+
114
  # Thêm một ô system_prompt
115
  @spaces.GPU(duration=60)
116
  def chat_with_model(prompt, system_prompt, chatbot_display, internal_history,lang,gender,progress=gr.Progress(track_tqdm=True)):