Create app.py
Browse files
app.py
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import torch
|
| 2 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer, pipeline
|
| 3 |
+
import gradio as gr
|
| 4 |
+
|
| 5 |
+
# Setup model dan tokenizer
|
| 6 |
+
torch.random.manual_seed(0)
|
| 7 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 8 |
+
"microsoft/Phi-3-mini-128k-instruct",
|
| 9 |
+
device_map="cpu", # Gunakan 'cpu' jika tidak ada GPU
|
| 10 |
+
torch_dtype="auto",
|
| 11 |
+
trust_remote_code=True,
|
| 12 |
+
attn_implementation="eager" # Menggunakan eager untuk menghindari masalah flash-attention
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
tokenizer = AutoTokenizer.from_pretrained("microsoft/Phi-3-mini-128k-instruct")
|
| 16 |
+
|
| 17 |
+
# Pipeline untuk text-generation
|
| 18 |
+
pipe = pipeline(
|
| 19 |
+
"text-generation",
|
| 20 |
+
model=model,
|
| 21 |
+
tokenizer=tokenizer,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
# Fungsi untuk menghasilkan respons
|
| 25 |
+
def generate_response(input_text):
|
| 26 |
+
messages = [
|
| 27 |
+
{"role": "system", "content": "You are a helpful AI assistant."},
|
| 28 |
+
{"role": "user", "content": input_text}
|
| 29 |
+
]
|
| 30 |
+
|
| 31 |
+
generation_args = {
|
| 32 |
+
"max_new_tokens": 500,
|
| 33 |
+
"return_full_text": False,
|
| 34 |
+
"temperature": 0.7, # Bisa disesuaikan untuk variasi output
|
| 35 |
+
"do_sample": True, # Mengaktifkan sampling untuk variasi output
|
| 36 |
+
}
|
| 37 |
+
|
| 38 |
+
output = pipe(messages, **generation_args)
|
| 39 |
+
return output[0]['generated_text']
|
| 40 |
+
|
| 41 |
+
# Membuat antarmuka menggunakan Gradio Blocks
|
| 42 |
+
with gr.Blocks() as demo:
|
| 43 |
+
gr.Markdown("# AI Chatbot Assistant\nTanya apapun, saya siap membantu!")
|
| 44 |
+
|
| 45 |
+
# Tata letak output di atas input
|
| 46 |
+
with gr.Row():
|
| 47 |
+
output_box = gr.Textbox(
|
| 48 |
+
label="AI Response",
|
| 49 |
+
placeholder="Respons akan muncul di sini...",
|
| 50 |
+
lines=10,
|
| 51 |
+
interactive=False # Tidak dapat diisi manual
|
| 52 |
+
)
|
| 53 |
+
with gr.Row():
|
| 54 |
+
input_box = gr.Textbox(label="Ask me anything!", placeholder="Tanyakan sesuatu...")
|
| 55 |
+
with gr.Row():
|
| 56 |
+
submit_button = gr.Button("Submit")
|
| 57 |
+
|
| 58 |
+
# Aksi untuk submit
|
| 59 |
+
submit_button.click(generate_response, inputs=input_box, outputs=output_box)
|
| 60 |
+
|
| 61 |
+
# Menjalankan antarmuka
|
| 62 |
+
demo.launch()
|