Update app.py
Browse files
app.py
CHANGED
@@ -1,98 +1,51 @@
|
|
1 |
import gradio as gr
|
2 |
-
from transformers import
|
3 |
-
from peft import PeftModel
|
4 |
-
import torch
|
5 |
import os
|
6 |
|
7 |
-
HF_TOKEN = os.environ
|
8 |
|
9 |
-
# Load the base model and adapter for Model 1
|
10 |
-
base_model_name = "google/gemma-2b-it" # or the correct base model
|
11 |
-
adapter_model_name = "akhaliq/gemma-3-270m-gradio-coder-adapter"
|
12 |
|
13 |
-
# Initialize
|
14 |
-
|
15 |
-
|
16 |
-
base_model1 = AutoModelForCausalLM.from_pretrained(
|
17 |
-
base_model_name,
|
18 |
-
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
19 |
-
device_map="auto" if torch.cuda.is_available() else None,
|
20 |
-
token=HF_TOKEN
|
21 |
-
)
|
22 |
-
model1 = PeftModel.from_pretrained(base_model1, adapter_model_name)
|
23 |
-
model1.eval()
|
24 |
|
25 |
-
|
26 |
-
print("Loading Model 2...")
|
27 |
-
model2_name = "google/gemma-2b-it" # Using gemma-2b-it as gemma-3-270m-it might not exist
|
28 |
-
tokenizer2 = AutoTokenizer.from_pretrained(model2_name, token=HF_TOKEN)
|
29 |
-
model2 = AutoModelForCausalLM.from_pretrained(
|
30 |
-
model2_name,
|
31 |
-
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
32 |
-
device_map="auto" if torch.cuda.is_available() else None,
|
33 |
-
token=HF_TOKEN
|
34 |
-
)
|
35 |
-
model2.eval()
|
36 |
-
|
37 |
-
def generate_code(user_input, model, tokenizer, model_name="Model"):
|
38 |
"""
|
39 |
-
Generate code based on user input using the selected model
|
40 |
"""
|
41 |
-
|
42 |
-
|
43 |
-
|
44 |
-
|
45 |
-
|
46 |
-
|
47 |
-
|
48 |
-
|
49 |
-
|
50 |
-
|
51 |
-
#
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
-
|
58 |
-
|
59 |
-
|
60 |
-
|
61 |
-
)
|
62 |
-
|
63 |
-
# Decode the output
|
64 |
-
generated_text = tokenizer.decode(outputs[0], skip_special_tokens=True)
|
65 |
-
|
66 |
-
# Extract only the model's response
|
67 |
-
if "<start_of_turn>model" in generated_text:
|
68 |
-
response = generated_text.split("<start_of_turn>model")[-1].strip()
|
69 |
-
elif user_input in generated_text:
|
70 |
-
response = generated_text.split(user_input)[-1].strip()
|
71 |
else:
|
72 |
-
|
73 |
-
|
74 |
-
|
75 |
-
|
76 |
-
|
77 |
-
return response
|
78 |
|
79 |
def generate_both(user_input):
|
80 |
"""
|
81 |
Generate code from both models for comparison
|
82 |
"""
|
83 |
-
|
84 |
-
|
85 |
-
|
86 |
-
try:
|
87 |
-
output1 = generate_code(user_input, model1, tokenizer1, "Model 1 (Adapter)")
|
88 |
-
except Exception as e:
|
89 |
-
output1 = f"Error with Model 1: {str(e)}"
|
90 |
-
|
91 |
-
try:
|
92 |
-
output2 = generate_code(user_input, model2, tokenizer2, "Model 2 (Base)")
|
93 |
-
except Exception as e:
|
94 |
-
output2 = f"Error with Model 2: {str(e)}"
|
95 |
-
|
96 |
return output1, output2
|
97 |
|
98 |
# Create the Gradio interface
|
@@ -102,8 +55,8 @@ with gr.Blocks(title="Text to Code Generator - Model Comparison", theme=gr.theme
|
|
102 |
# π Text to Code Generator - Model Comparison
|
103 |
|
104 |
Compare code generation from two different Gemma models:
|
105 |
-
- **Model 1**:
|
106 |
-
- **Model 2**:
|
107 |
|
108 |
Simply describe what you want to build, and see how each model responds!
|
109 |
"""
|
@@ -131,7 +84,6 @@ with gr.Blocks(title="Text to Code Generator - Model Comparison", theme=gr.theme
|
|
131 |
["Create a React component for a todo list item"],
|
132 |
["Write a SQL query to find the top 5 customers by total purchase amount"],
|
133 |
["Create a Python class for a bank account with deposit and withdraw methods"],
|
134 |
-
["Build a simple Gradio interface for text summarization"],
|
135 |
],
|
136 |
inputs=input_text,
|
137 |
label="Example Prompts"
|
@@ -141,27 +93,31 @@ with gr.Blocks(title="Text to Code Generator - Model Comparison", theme=gr.theme
|
|
141 |
# Output section - Two columns for comparison
|
142 |
with gr.Row():
|
143 |
with gr.Column():
|
144 |
-
gr.Markdown("### Model 1:
|
145 |
output_code1 = gr.Code(
|
146 |
label="Generated Code (Model 1)",
|
147 |
language="python",
|
148 |
lines=15,
|
149 |
interactive=True,
|
150 |
-
|
|
|
|
|
151 |
)
|
152 |
-
copy_btn1 = gr.Button("π Copy Code",
|
153 |
|
154 |
with gr.Column():
|
155 |
-
gr.Markdown("### Model 2:
|
156 |
output_code2 = gr.Code(
|
157 |
label="Generated Code (Model 2)",
|
158 |
language="python",
|
159 |
lines=15,
|
160 |
interactive=True,
|
161 |
-
|
|
|
|
|
162 |
)
|
163 |
-
copy_btn2 = gr.Button("π Copy Code",
|
164 |
-
|
165 |
# Add event handlers
|
166 |
generate_btn.click(
|
167 |
fn=generate_both,
|
@@ -178,33 +134,26 @@ with gr.Blocks(title="Text to Code Generator - Model Comparison", theme=gr.theme
|
|
178 |
|
179 |
# Copy functionality for both outputs
|
180 |
copy_btn1.click(
|
181 |
-
None,
|
182 |
inputs=output_code1,
|
183 |
outputs=None,
|
184 |
js="""
|
185 |
(code) => {
|
186 |
navigator.clipboard.writeText(code);
|
187 |
-
|
188 |
-
const originalText = btn.textContent;
|
189 |
-
btn.textContent = 'β Copied!';
|
190 |
-
setTimeout(() => btn.textContent = originalText, 2000);
|
191 |
return null;
|
192 |
}
|
193 |
"""
|
194 |
)
|
195 |
|
196 |
copy_btn2.click(
|
197 |
-
None,
|
198 |
inputs=output_code2,
|
199 |
outputs=None,
|
200 |
js="""
|
201 |
(code) => {
|
202 |
navigator.clipboard.writeText(code);
|
203 |
-
|
204 |
-
const btn = btns[1];
|
205 |
-
const originalText = btn.textContent;
|
206 |
-
btn.textContent = 'β Copied!';
|
207 |
-
setTimeout(() => btn.textContent = originalText, 2000);
|
208 |
return null;
|
209 |
}
|
210 |
"""
|
@@ -219,7 +168,9 @@ with gr.Blocks(title="Text to Code Generator - Model Comparison", theme=gr.theme
|
|
219 |
- Include details about inputs, outputs, and edge cases
|
220 |
- You can edit the generated code directly in the output box
|
221 |
|
222 |
-
**
|
|
|
|
|
223 |
"""
|
224 |
)
|
225 |
|
|
|
1 |
import gradio as gr
|
2 |
+
from transformers import pipeline
|
|
|
|
|
3 |
import os
|
4 |
|
5 |
+
HF_TOKEN = os.environ["HF_TOKEN"]
|
6 |
|
|
|
|
|
|
|
7 |
|
8 |
+
# Initialize the text generation pipelines
|
9 |
+
pipe = pipeline("text-generation", model="akhaliq/MyGemmaGradioCoder")
|
10 |
+
pipe2 = pipeline("text-generation", model="google/gemma-3-270m-it", token=HF_TOKEN)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
11 |
|
12 |
+
def generate_code(user_input, model_choice="Model 1"):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
13 |
"""
|
14 |
+
Generate code based on user input using the selected Gemma model
|
15 |
"""
|
16 |
+
messages = [
|
17 |
+
{"role": "user", "content": user_input},
|
18 |
+
]
|
19 |
+
|
20 |
+
# Select pipeline based on model choice
|
21 |
+
selected_pipe = pipe if model_choice == "Model 1 (MyGemmaGradioCoder)" else pipe2
|
22 |
+
|
23 |
+
# Generate response from the model
|
24 |
+
response = selected_pipe(messages, max_new_tokens=512, temperature=0.7, do_sample=True)
|
25 |
+
|
26 |
+
# Extract the generated text from the response
|
27 |
+
generated_text = response[0]['generated_text']
|
28 |
+
|
29 |
+
# If the response contains the full conversation, extract just the assistant's response
|
30 |
+
if isinstance(generated_text, list):
|
31 |
+
# Handle conversation format
|
32 |
+
for msg in generated_text:
|
33 |
+
if msg.get('role') == 'assistant':
|
34 |
+
return msg.get('content', '')
|
35 |
+
# If no assistant message found, return the last message content
|
36 |
+
return generated_text[-1].get('content', '') if generated_text else ""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
37 |
else:
|
38 |
+
# Handle string format - try to extract the code after the user input
|
39 |
+
if user_input in generated_text:
|
40 |
+
return generated_text.split(user_input)[-1].strip()
|
41 |
+
return generated_text
|
|
|
|
|
42 |
|
43 |
def generate_both(user_input):
|
44 |
"""
|
45 |
Generate code from both models for comparison
|
46 |
"""
|
47 |
+
output1 = generate_code(user_input, "Model 1 (MyGemmaGradioCoder)")
|
48 |
+
output2 = generate_code(user_input, "Model 2 (gemma-3-270m-it)")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
49 |
return output1, output2
|
50 |
|
51 |
# Create the Gradio interface
|
|
|
55 |
# π Text to Code Generator - Model Comparison
|
56 |
|
57 |
Compare code generation from two different Gemma models:
|
58 |
+
- **Model 1**: akhaliq/MyGemmaGradioCoder
|
59 |
+
- **Model 2**: google/gemma-3-270m-it
|
60 |
|
61 |
Simply describe what you want to build, and see how each model responds!
|
62 |
"""
|
|
|
84 |
["Create a React component for a todo list item"],
|
85 |
["Write a SQL query to find the top 5 customers by total purchase amount"],
|
86 |
["Create a Python class for a bank account with deposit and withdraw methods"],
|
|
|
87 |
],
|
88 |
inputs=input_text,
|
89 |
label="Example Prompts"
|
|
|
93 |
# Output section - Two columns for comparison
|
94 |
with gr.Row():
|
95 |
with gr.Column():
|
96 |
+
gr.Markdown("### Model 1: MyGemmaGradioCoder")
|
97 |
output_code1 = gr.Code(
|
98 |
label="Generated Code (Model 1)",
|
99 |
language="python",
|
100 |
lines=15,
|
101 |
interactive=True,
|
102 |
+
show_line_numbers=True,
|
103 |
+
wrap_lines=True,
|
104 |
+
autocomplete=True
|
105 |
)
|
106 |
+
copy_btn1 = gr.Button("π Copy Code", scale=1)
|
107 |
|
108 |
with gr.Column():
|
109 |
+
gr.Markdown("### Model 2: gemma-3-270m-it")
|
110 |
output_code2 = gr.Code(
|
111 |
label="Generated Code (Model 2)",
|
112 |
language="python",
|
113 |
lines=15,
|
114 |
interactive=True,
|
115 |
+
show_line_numbers=True,
|
116 |
+
wrap_lines=True,
|
117 |
+
autocomplete=True
|
118 |
)
|
119 |
+
copy_btn2 = gr.Button("π Copy Code", scale=1)
|
120 |
+
|
121 |
# Add event handlers
|
122 |
generate_btn.click(
|
123 |
fn=generate_both,
|
|
|
134 |
|
135 |
# Copy functionality for both outputs
|
136 |
copy_btn1.click(
|
137 |
+
fn=None,
|
138 |
inputs=output_code1,
|
139 |
outputs=None,
|
140 |
js="""
|
141 |
(code) => {
|
142 |
navigator.clipboard.writeText(code);
|
143 |
+
alert('Code from Model 1 copied to clipboard!');
|
|
|
|
|
|
|
144 |
return null;
|
145 |
}
|
146 |
"""
|
147 |
)
|
148 |
|
149 |
copy_btn2.click(
|
150 |
+
fn=None,
|
151 |
inputs=output_code2,
|
152 |
outputs=None,
|
153 |
js="""
|
154 |
(code) => {
|
155 |
navigator.clipboard.writeText(code);
|
156 |
+
alert('Code from Model 2 copied to clipboard!');
|
|
|
|
|
|
|
|
|
157 |
return null;
|
158 |
}
|
159 |
"""
|
|
|
168 |
- Include details about inputs, outputs, and edge cases
|
169 |
- You can edit the generated code directly in the output box
|
170 |
|
171 |
+
**Models:**
|
172 |
+
- [akhaliq/MyGemmaGradioCoder](https://huggingface.co/akhaliq/MyGemmaGradioCoder)
|
173 |
+
- [google/gemma-3-270m-it](https://huggingface.co/google/gemma-3-270m-it)
|
174 |
"""
|
175 |
)
|
176 |
|