Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -3,65 +3,81 @@ import torch
|
|
| 3 |
import sys
|
| 4 |
import subprocess
|
| 5 |
|
| 6 |
-
#
|
| 7 |
-
def
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
|
| 17 |
-
|
| 18 |
|
| 19 |
-
from transformers import
|
| 20 |
-
from peft import PeftModel
|
| 21 |
|
| 22 |
-
#
|
| 23 |
-
|
|
|
|
| 24 |
|
| 25 |
-
print(
|
|
|
|
|
|
|
|
|
|
| 26 |
|
| 27 |
try:
|
| 28 |
-
# Load tokenizer dari adapter
|
| 29 |
-
tokenizer
|
|
|
|
| 30 |
|
| 31 |
-
# Load base model
|
| 32 |
-
print("
|
| 33 |
-
base_model =
|
| 34 |
|
| 35 |
-
# Load adapter
|
| 36 |
-
print("
|
| 37 |
-
model = PeftModel.from_pretrained(base_model,
|
| 38 |
|
| 39 |
-
# Merge adapter
|
|
|
|
| 40 |
model = model.merge_and_unload()
|
| 41 |
|
| 42 |
-
print("β
PEFT model loaded and merged
|
| 43 |
|
| 44 |
except Exception as e:
|
| 45 |
-
print(f"β Error
|
| 46 |
-
print("π Falling back to plain
|
| 47 |
-
tokenizer =
|
| 48 |
-
model =
|
| 49 |
|
| 50 |
-
#
|
| 51 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 52 |
-
print(f"π±
|
| 53 |
model.to(device)
|
| 54 |
model.eval()
|
| 55 |
|
| 56 |
def generate_code(instruction, max_length=150, temperature=0.7):
|
| 57 |
-
"""
|
| 58 |
-
Generate Python code from instruction
|
| 59 |
-
"""
|
| 60 |
try:
|
| 61 |
-
#
|
| 62 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
-
# Tokenize
|
| 65 |
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=128).to(device)
|
| 66 |
|
| 67 |
# Generate
|
|
@@ -74,59 +90,66 @@ def generate_code(instruction, max_length=150, temperature=0.7):
|
|
| 74 |
num_return_sequences=1,
|
| 75 |
pad_token_id=tokenizer.pad_token_id,
|
| 76 |
eos_token_id=tokenizer.eos_token_id,
|
| 77 |
-
repetition_penalty=1.
|
|
|
|
| 78 |
)
|
| 79 |
|
| 80 |
-
# Decode
|
| 81 |
generated = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 82 |
|
| 83 |
-
# Clean
|
| 84 |
if generated.startswith(prompt):
|
| 85 |
generated = generated[len(prompt):].strip()
|
| 86 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 87 |
return generated
|
| 88 |
|
| 89 |
except Exception as e:
|
| 90 |
-
return f"Error
|
| 91 |
|
| 92 |
-
# Create Gradio Interface
|
| 93 |
with gr.Blocks(title="Daffa AI Coder") as demo:
|
| 94 |
gr.Markdown("# π Daffa AI Coder")
|
| 95 |
-
gr.Markdown("
|
| 96 |
|
| 97 |
with gr.Row():
|
| 98 |
-
with gr.Column(
|
| 99 |
-
# Input
|
| 100 |
instruction = gr.Textbox(
|
| 101 |
-
label="
|
| 102 |
-
placeholder="
|
| 103 |
-
lines=3
|
| 104 |
-
value="Buat fungsi Python untuk menghitung luas lingkaran"
|
| 105 |
)
|
| 106 |
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
label="Panjang Maksimal",
|
| 111 |
-
minimum=50,
|
| 112 |
-
maximum=300,
|
| 113 |
-
value=150,
|
| 114 |
-
step=10
|
| 115 |
-
)
|
| 116 |
-
temperature = gr.Slider(
|
| 117 |
-
label="Temperature (kreativitas)",
|
| 118 |
-
minimum=0.1,
|
| 119 |
-
maximum=1.5,
|
| 120 |
-
value=0.7,
|
| 121 |
-
step=0.1
|
| 122 |
-
)
|
| 123 |
|
| 124 |
-
generate_btn = gr.Button("
|
| 125 |
-
clear_btn = gr.Button("ποΈ Clear")
|
| 126 |
|
| 127 |
-
with gr.Column(
|
| 128 |
-
|
| 129 |
-
output_code = gr.Code(
|
| 130 |
label="Generated Python Code",
|
| 131 |
language="python",
|
| 132 |
lines=15
|
|
@@ -134,51 +157,26 @@ with gr.Blocks(title="Daffa AI Coder") as demo:
|
|
| 134 |
|
| 135 |
# Examples
|
| 136 |
examples = [
|
| 137 |
-
["
|
| 138 |
-
["
|
| 139 |
-
["
|
| 140 |
-
["
|
| 141 |
-
["
|
| 142 |
]
|
| 143 |
|
| 144 |
gr.Examples(
|
| 145 |
examples=examples,
|
| 146 |
inputs=instruction,
|
| 147 |
-
|
| 148 |
-
|
| 149 |
-
|
| 150 |
-
# Events
|
| 151 |
-
generate_btn.click(
|
| 152 |
-
fn=generate_code,
|
| 153 |
-
inputs=[instruction, max_length, temperature],
|
| 154 |
-
outputs=output_code
|
| 155 |
-
)
|
| 156 |
-
|
| 157 |
-
clear_btn.click(
|
| 158 |
-
fn=lambda: ("", ""),
|
| 159 |
-
inputs=[],
|
| 160 |
-
outputs=[instruction, output_code]
|
| 161 |
)
|
| 162 |
|
|
|
|
| 163 |
gr.Markdown("---")
|
| 164 |
-
gr.Markdown("
|
| 165 |
-
gr.Markdown("""
|
| 166 |
-
**Model Details:**
|
| 167 |
-
- Base Model: T5-small
|
| 168 |
-
- Fine-tuning: LoRA (Low-Rank Adaptation)
|
| 169 |
-
- Adapter Size: 600 KB
|
| 170 |
-
- Task: Text-to-Text Generation
|
| 171 |
|
| 172 |
-
|
| 173 |
-
|
| 174 |
-
- Mendukung berbagai fungsi Python dasar
|
| 175 |
-
- Cocok untuk pembelajaran dan prototyping
|
| 176 |
-
""")
|
| 177 |
|
| 178 |
-
|
| 179 |
-
if __name__ == "__main__":
|
| 180 |
-
demo.launch(
|
| 181 |
-
server_name="0.0.0.0",
|
| 182 |
-
server_port=7860,
|
| 183 |
-
share=False
|
| 184 |
-
)
|
|
|
|
| 3 |
import sys
|
| 4 |
import subprocess
|
| 5 |
|
| 6 |
+
# Install required packages
|
| 7 |
+
def install_packages():
|
| 8 |
+
packages = ["peft==0.7.0", "sentencepiece==0.1.99", "protobuf==3.20.3"]
|
| 9 |
+
for package in packages:
|
| 10 |
+
try:
|
| 11 |
+
__import__(package.split('==')[0])
|
| 12 |
+
print(f"β
{package} already installed")
|
| 13 |
+
except ImportError:
|
| 14 |
+
print(f"π¦ Installing {package}...")
|
| 15 |
+
subprocess.check_call([sys.executable, "-m", "pip", "install", package])
|
| 16 |
|
| 17 |
+
install_packages()
|
| 18 |
|
| 19 |
+
from transformers import T5Tokenizer, T5ForConditionalGeneration
|
| 20 |
+
from peft import PeftModel
|
| 21 |
|
| 22 |
+
# Configuration
|
| 23 |
+
PEFT_MODEL_ID = "daffaaditya/daffa-ai"
|
| 24 |
+
BASE_MODEL = "t5-small"
|
| 25 |
|
| 26 |
+
print("=" * 50)
|
| 27 |
+
print(f"π Loading PEFT Adapter: {PEFT_MODEL_ID}")
|
| 28 |
+
print(f"π¦ Base Model: {BASE_MODEL}")
|
| 29 |
+
print("=" * 50)
|
| 30 |
|
| 31 |
try:
|
| 32 |
+
# Load tokenizer dari BASE MODEL, bukan dari adapter
|
| 33 |
+
print("1. Loading tokenizer from base model...")
|
| 34 |
+
tokenizer = T5Tokenizer.from_pretrained(BASE_MODEL)
|
| 35 |
|
| 36 |
+
# Load base model
|
| 37 |
+
print("2. Loading base model...")
|
| 38 |
+
base_model = T5ForConditionalGeneration.from_pretrained(BASE_MODEL)
|
| 39 |
|
| 40 |
+
# Load adapter
|
| 41 |
+
print("3. Loading adapter...")
|
| 42 |
+
model = PeftModel.from_pretrained(base_model, PEFT_MODEL_ID)
|
| 43 |
|
| 44 |
+
# Merge adapter (optional, tapi lebih cepat untuk inference)
|
| 45 |
+
print("4. Merging adapter with base model...")
|
| 46 |
model = model.merge_and_unload()
|
| 47 |
|
| 48 |
+
print("β
SUCCESS: PEFT model loaded and merged!")
|
| 49 |
|
| 50 |
except Exception as e:
|
| 51 |
+
print(f"β Error: {e}")
|
| 52 |
+
print("π Falling back to plain T5-small without adapter...")
|
| 53 |
+
tokenizer = T5Tokenizer.from_pretrained(BASE_MODEL)
|
| 54 |
+
model = T5ForConditionalGeneration.from_pretrained(BASE_MODEL)
|
| 55 |
|
| 56 |
+
# Setup device
|
| 57 |
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 58 |
+
print(f"π± Device: {device}")
|
| 59 |
model.to(device)
|
| 60 |
model.eval()
|
| 61 |
|
| 62 |
def generate_code(instruction, max_length=150, temperature=0.7):
|
| 63 |
+
"""Generate Python code from instruction"""
|
|
|
|
|
|
|
| 64 |
try:
|
| 65 |
+
# Clean instruction
|
| 66 |
+
instruction = instruction.strip()
|
| 67 |
+
|
| 68 |
+
# Format prompt lebih baik
|
| 69 |
+
if "prima" in instruction.lower():
|
| 70 |
+
prompt = "Write a Python function to check if a number is prime:"
|
| 71 |
+
elif "faktorial" in instruction.lower():
|
| 72 |
+
prompt = "Write a Python function to calculate factorial:"
|
| 73 |
+
elif "reverse" in instruction.lower():
|
| 74 |
+
prompt = "Write a Python function to reverse a string:"
|
| 75 |
+
elif "lingkaran" in instruction.lower() or "circle" in instruction.lower():
|
| 76 |
+
prompt = "Write a Python function to calculate circle area:"
|
| 77 |
+
else:
|
| 78 |
+
prompt = f"Write Python code for: {instruction}"
|
| 79 |
|
| 80 |
+
# Tokenize
|
| 81 |
inputs = tokenizer(prompt, return_tensors="pt", truncation=True, max_length=128).to(device)
|
| 82 |
|
| 83 |
# Generate
|
|
|
|
| 90 |
num_return_sequences=1,
|
| 91 |
pad_token_id=tokenizer.pad_token_id,
|
| 92 |
eos_token_id=tokenizer.eos_token_id,
|
| 93 |
+
repetition_penalty=1.3,
|
| 94 |
+
no_repeat_ngram_size=3
|
| 95 |
)
|
| 96 |
|
| 97 |
+
# Decode
|
| 98 |
generated = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
| 99 |
|
| 100 |
+
# Clean output
|
| 101 |
if generated.startswith(prompt):
|
| 102 |
generated = generated[len(prompt):].strip()
|
| 103 |
|
| 104 |
+
# Jika output kosong atau pendek
|
| 105 |
+
if len(generated) < 10:
|
| 106 |
+
# Fallback templates
|
| 107 |
+
fallbacks = {
|
| 108 |
+
"prima": """def is_prime(n):
|
| 109 |
+
if n < 2:
|
| 110 |
+
return False
|
| 111 |
+
for i in range(2, int(n**0.5) + 1):
|
| 112 |
+
if n % i == 0:
|
| 113 |
+
return False
|
| 114 |
+
return True""",
|
| 115 |
+
"faktorial": """def factorial(n):
|
| 116 |
+
if n == 0:
|
| 117 |
+
return 1
|
| 118 |
+
return n * factorial(n-1)""",
|
| 119 |
+
"reverse": """def reverse_string(s):
|
| 120 |
+
return s[::-1]"""
|
| 121 |
+
}
|
| 122 |
+
|
| 123 |
+
for key, code in fallbacks.items():
|
| 124 |
+
if key in instruction.lower():
|
| 125 |
+
return code
|
| 126 |
+
|
| 127 |
return generated
|
| 128 |
|
| 129 |
except Exception as e:
|
| 130 |
+
return f"# Error\n# {str(e)}\n\nPlease try a different prompt."
|
| 131 |
|
| 132 |
+
# Create Gradio Interface
|
| 133 |
with gr.Blocks(title="Daffa AI Coder") as demo:
|
| 134 |
gr.Markdown("# π Daffa AI Coder")
|
| 135 |
+
gr.Markdown("Fine-tuned T5 model for Python code generation")
|
| 136 |
|
| 137 |
with gr.Row():
|
| 138 |
+
with gr.Column():
|
|
|
|
| 139 |
instruction = gr.Textbox(
|
| 140 |
+
label="Instruction (Indonesian/English)",
|
| 141 |
+
placeholder="Example: buat fungsi untuk cek bilangan prima",
|
| 142 |
+
lines=3
|
|
|
|
| 143 |
)
|
| 144 |
|
| 145 |
+
with gr.Accordion("βοΈ Settings", open=False):
|
| 146 |
+
max_length = gr.Slider(50, 300, value=150, label="Max Length")
|
| 147 |
+
temperature = gr.Slider(0.1, 1.5, value=0.7, label="Temperature")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 148 |
|
| 149 |
+
generate_btn = gr.Button("Generate Code", variant="primary")
|
|
|
|
| 150 |
|
| 151 |
+
with gr.Column():
|
| 152 |
+
output = gr.Code(
|
|
|
|
| 153 |
label="Generated Python Code",
|
| 154 |
language="python",
|
| 155 |
lines=15
|
|
|
|
| 157 |
|
| 158 |
# Examples
|
| 159 |
examples = [
|
| 160 |
+
["buat fungsi untuk cek bilangan prima"],
|
| 161 |
+
["create a function to calculate factorial"],
|
| 162 |
+
["write a function to reverse a string"],
|
| 163 |
+
["fungsi untuk menghitung luas lingkaran"],
|
| 164 |
+
["function to convert celsius to fahrenheit"]
|
| 165 |
]
|
| 166 |
|
| 167 |
gr.Examples(
|
| 168 |
examples=examples,
|
| 169 |
inputs=instruction,
|
| 170 |
+
outputs=output,
|
| 171 |
+
fn=lambda x: generate_code(x, 150, 0.7),
|
| 172 |
+
label="Try these examples:"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
)
|
| 174 |
|
| 175 |
+
# Footer
|
| 176 |
gr.Markdown("---")
|
| 177 |
+
gr.Markdown(f"**Model:** {PEFT_MODEL_ID} | **Base:** {BASE_MODEL} | **Status:** {'Adapter Loaded' if 'PeftModel' in str(type(model)) else 'Base Model Only'}")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 178 |
|
| 179 |
+
# Events
|
| 180 |
+
generate_btn.click(generate_code, [instruction, max_length, temperature], output)
|
|
|
|
|
|
|
|
|
|
| 181 |
|
| 182 |
+
demo.launch()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|