| | import gradio as gr |
| | import torch |
| | from transformers import AutoTokenizer, AutoModelForCausalLM |
| | import os |
| | from huggingface_hub import login |
| |
|
| | |
| | |
| | model_id = "google/gemma-3n-E4B-it-litert-preview" |
| | |
| | |
| | hf_token = os.getenv("HF_TOKEN") |
| |
|
| | |
| | if hf_token: |
| | print("Melakukan login ke Hugging Face Hub...") |
| | login(token=hf_token) |
| | else: |
| | print("Peringatan: Secret HF_TOKEN tidak ditemukan. Proses unduh model mungkin gagal jika repo bersifat privat/gated.") |
| |
|
| | |
| | |
| | print("Memuat tokenizer...") |
| | |
| | |
| | tokenizer = AutoTokenizer.from_pretrained( |
| | model_id, |
| | trust_remote_code=True |
| | ) |
| |
|
| | print("Memuat model... Ini mungkin memakan waktu beberapa menit.") |
| | |
| | |
| | |
| | model = AutoModelForCausalLM.from_pretrained( |
| | model_id, |
| | torch_dtype=torch.bfloat16, |
| | device_map="auto", |
| | trust_remote_code=True, |
| | ) |
| | print("Model berhasil dimuat!") |
| |
|
| | |
| | def chat_function(message, history): |
| | """ |
| | Fungsi ini dipanggil setiap kali pengguna mengirim pesan. |
| | Ia memformat input, menghasilkan respons dari model, dan mengembalikan hasilnya. |
| | """ |
| | |
| | |
| | chat_template = [] |
| | for user_msg, assistant_msg in history: |
| | chat_template.append({"role": "user", "content": user_msg}) |
| | chat_template.append({"role": "assistant", "content": assistant_msg}) |
| | |
| | |
| | chat_template.append({"role": "user", "content": message}) |
| | |
| | |
| | |
| | prompt = tokenizer.apply_chat_template(chat_template, tokenize=False, add_generation_prompt=True) |
| |
|
| | |
| | inputs = tokenizer(prompt, return_tensors="pt").to(model.device) |
| |
|
| | print("\n--- Menghasilkan Respons ---") |
| | print(f"Prompt yang dikirim ke model:\n{prompt}") |
| |
|
| | |
| | outputs = model.generate( |
| | **inputs, |
| | max_new_tokens=1500, |
| | eos_token_id=tokenizer.eos_token_id |
| | ) |
| | |
| | |
| | |
| | response_text = tokenizer.decode(outputs[0][len(inputs.input_ids[0]):], skip_special_tokens=True) |
| | |
| | print(f"Respons dari model:\n{response_text}") |
| | return response_text |
| |
|
| | |
| | |
| | chatbot_ui = gr.ChatInterface( |
| | fn=chat_function, |
| | title="🤖 Gemma 3n Chat", |
| | description=""" |
| | Ini adalah antarmuka chat untuk model **google/gemma-3n-E4B-it-litert-preview**. |
| | Model ini adalah model besar, jadi harap bersabar untuk responsnya jika berjalan di CPU. |
| | **Sangat disarankan untuk menggunakan hardware GPU untuk performa terbaik.** |
| | """, |
| | examples=[ |
| | ["Ceritakan tentang sejarah singkat Indonesia"], |
| | ["Buatkan saya resep untuk membuat nasi goreng spesial"], |
| | ["Jelaskan konsep machine learning dalam 3 paragraf"] |
| | ], |
| | cache_examples=False |
| | ).queue() |
| |
|
| | |
| | if __name__ == "__main__": |
| | chatbot_ui.launch() |
| |
|