TaruniSwathi commited on
Commit
3f66bfa
Β·
verified Β·
1 Parent(s): cf80c78

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +260 -0
app.py ADDED
@@ -0,0 +1,260 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import re
3
+ import threading
4
+
5
+ import gradio as gr
6
+ from huggingface_hub import hf_hub_download
7
+ from llama_cpp import Llama
8
+
9
+
10
+ MODEL_REPO = "TaruniSwathi/Qwen2.5-Coder-1.5B-Java-CSharp-GGUF"
11
+ MODEL_FILE = "Qwen2.5-Coder-1.5B-Java-CSharp_V2.Q4_K_M.gguf"
12
+
13
+ STAGE1_RESPONSE_MARKER = "### Response:\n\n"
14
+ STAGE2_RESPONSE_MARKER = "### Response\n"
15
+
16
+ # Prevent two users from running CPU inference simultaneously.
17
+ generation_lock = threading.Lock()
18
+
19
+
20
+ print("Downloading GGUF model...")
21
+
22
+ model_path = hf_hub_download(
23
+ repo_id=MODEL_REPO,
24
+ filename=MODEL_FILE,
25
+ )
26
+
27
+ print("Loading GGUF model...")
28
+
29
+ llm = Llama(
30
+ model_path=model_path,
31
+ n_ctx=4096,
32
+ n_threads=max(1, os.cpu_count() or 2),
33
+ n_threads_batch=max(1, os.cpu_count() or 2),
34
+ n_batch=128,
35
+ n_gpu_layers=0,
36
+ verbose=False,
37
+ )
38
+
39
+ print("Model loaded successfully.")
40
+
41
+
42
+ def add_java_hint(instruction: str) -> str:
43
+ instruction = instruction.strip()
44
+
45
+ if "java" in instruction.lower():
46
+ return instruction
47
+
48
+ return f"{instruction} Write the solution in Java."
49
+
50
+
51
+ def build_nl_to_java_prompt(instruction: str) -> str:
52
+ return (
53
+ "### Instruction:\n\n"
54
+ f"{add_java_hint(instruction)}\n\n"
55
+ "### Response:\n\n"
56
+ )
57
+
58
+
59
+ def build_java_to_csharp_prompt(java_code: str) -> str:
60
+ return (
61
+ "### Instruction\n"
62
+ "Translate the following Java code into equivalent C#. "
63
+ "Write the solution in C#.\n\n"
64
+ "### Java\n"
65
+ f"{java_code.strip()}\n\n"
66
+ "### Response\n"
67
+ )
68
+
69
+
70
+ def clean_generated_code(text: str) -> str:
71
+ text = text.strip()
72
+
73
+ # Remove Markdown code fences if the model adds them.
74
+ fenced = re.search(
75
+ r"```(?:java|csharp|cs|c#)?\s*(.*?)```",
76
+ text,
77
+ flags=re.DOTALL | re.IGNORECASE,
78
+ )
79
+
80
+ if fenced:
81
+ text = fenced.group(1).strip()
82
+
83
+ stop_markers = [
84
+ "### Instruction:",
85
+ "### Instruction\n",
86
+ "### Java:",
87
+ "### Java\n",
88
+ "### Response:",
89
+ "### Response\n",
90
+ "<|im_start|>",
91
+ "<|im_end|>",
92
+ ]
93
+
94
+ for marker in stop_markers:
95
+ if marker in text:
96
+ text = text.split(marker, 1)[0].strip()
97
+
98
+ return text
99
+
100
+
101
+ def run_generation(prompt: str, max_tokens: int) -> str:
102
+ with generation_lock:
103
+ response = llm(
104
+ prompt=prompt,
105
+ max_tokens=max_tokens,
106
+ temperature=0.0,
107
+ top_p=1.0,
108
+ repeat_penalty=1.0,
109
+ echo=False,
110
+ stop=[
111
+ "</s>",
112
+ "<|endoftext|>",
113
+ "<|im_end|>",
114
+ "### Instruction:",
115
+ "### Instruction\n",
116
+ ],
117
+ )
118
+
119
+ return response["choices"][0]["text"]
120
+
121
+
122
+ def generate_code(task: str, user_input: str) -> str:
123
+ if not user_input or not user_input.strip():
124
+ return "Please enter a requirement or Java code."
125
+
126
+ try:
127
+ if task == "Natural Language β†’ Java":
128
+ prompt = build_nl_to_java_prompt(user_input)
129
+ generated = run_generation(prompt, max_tokens=300)
130
+ language = "java"
131
+
132
+ else:
133
+ prompt = build_java_to_csharp_prompt(user_input)
134
+ generated = run_generation(prompt, max_tokens=400)
135
+ language = "csharp"
136
+
137
+ code = clean_generated_code(generated)
138
+
139
+ if not code:
140
+ return "The model returned an empty response. Please try again."
141
+
142
+ return f"```{language}\n{code}\n```"
143
+
144
+ except Exception as error:
145
+ return (
146
+ "Generation failed.\n\n"
147
+ f"Error: {type(error).__name__}: {error}"
148
+ )
149
+
150
+
151
+ def update_input(task: str):
152
+ if task == "Natural Language β†’ Java":
153
+ return gr.update(
154
+ label="Natural-language requirement",
155
+ placeholder=(
156
+ "Example: Write a Java method to check whether "
157
+ "a number is prime."
158
+ ),
159
+ value="",
160
+ )
161
+
162
+ return gr.update(
163
+ label="Java code",
164
+ placeholder=(
165
+ "Example:\n"
166
+ "public static int factorial(int n) {\n"
167
+ " int result = 1;\n"
168
+ " for (int i = 2; i <= n; i++) {\n"
169
+ " result *= i;\n"
170
+ " }\n"
171
+ " return result;\n"
172
+ "}"
173
+ ),
174
+ value="",
175
+ )
176
+
177
+
178
+ with gr.Blocks(title="Java and C# CodeGen") as demo:
179
+ gr.Markdown(
180
+ """
181
+ # Java and C# CodeGen
182
+
183
+ Generate Java code from natural-language requirements or translate Java code
184
+ into equivalent C# using a fine-tuned Qwen2.5-Coder model.
185
+ """
186
+ )
187
+
188
+ task = gr.Dropdown(
189
+ choices=[
190
+ "Natural Language β†’ Java",
191
+ "Java β†’ C#",
192
+ ],
193
+ value="Natural Language β†’ Java",
194
+ label="Select task",
195
+ )
196
+
197
+ user_input = gr.Textbox(
198
+ label="Natural-language requirement",
199
+ placeholder=(
200
+ "Example: Write a Java method to check whether "
201
+ "a number is prime."
202
+ ),
203
+ lines=14,
204
+ )
205
+
206
+ generate_button = gr.Button(
207
+ "Generate Code",
208
+ variant="primary",
209
+ )
210
+
211
+ output = gr.Markdown()
212
+
213
+ task.change(
214
+ fn=update_input,
215
+ inputs=task,
216
+ outputs=user_input,
217
+ )
218
+
219
+ generate_button.click(
220
+ fn=generate_code,
221
+ inputs=[
222
+ task,
223
+ user_input,
224
+ ],
225
+ outputs=output,
226
+ )
227
+
228
+ gr.Examples(
229
+ examples=[
230
+ [
231
+ "Natural Language β†’ Java",
232
+ "Write a Java method to calculate factorial of a number using a loop.",
233
+ ],
234
+ [
235
+ "Natural Language β†’ Java",
236
+ "Write a Java method to reverse a string.",
237
+ ],
238
+ [
239
+ "Java β†’ C#",
240
+ """public static int factorial(int n) {
241
+ int result = 1;
242
+ for (int i = 2; i <= n; i++) {
243
+ result *= i;
244
+ }
245
+ return result;
246
+ }""",
247
+ ],
248
+ ],
249
+ inputs=[
250
+ task,
251
+ user_input,
252
+ ],
253
+ )
254
+
255
+
256
+ if __name__ == "__main__":
257
+ demo.queue(
258
+ default_concurrency_limit=1,
259
+ max_size=10,
260
+ ).launch()