TaruniSwathi commited on
Commit
98ac7c0
·
verified ·
1 Parent(s): aed60de

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +105 -76
app.py CHANGED
@@ -1,4 +1,6 @@
1
  import os
 
 
2
 
3
  import gradio as gr
4
  from huggingface_hub import hf_hub_download
@@ -8,6 +10,12 @@ from llama_cpp import Llama
8
  MODEL_REPO = "TaruniSwathi/Qwen2.5-Coder-1.5B-Java-CSharp-GGUF"
9
  MODEL_FILE = "Qwen2.5-Coder-1.5B-Java-CSharp_V2.Q4_K_M.gguf"
10
 
 
 
 
 
 
 
11
 
12
  print("Downloading GGUF model...")
13
 
@@ -16,14 +24,13 @@ model_path = hf_hub_download(
16
  filename=MODEL_FILE,
17
  )
18
 
19
- print("Model downloaded:", model_path)
20
- print("Loading model with llama.cpp...")
21
-
22
 
23
  llm = Llama(
24
  model_path=model_path,
25
- n_ctx=2048,
26
  n_threads=max(1, os.cpu_count() or 2),
 
27
  n_batch=128,
28
  n_gpu_layers=0,
29
  verbose=False,
@@ -32,84 +39,116 @@ llm = Llama(
32
  print("Model loaded successfully.")
33
 
34
 
35
- def build_prompt(task: str, user_input: str) -> str:
36
- user_input = user_input.strip()
37
 
38
- if task == "Natural Language → Java":
39
- return f"""### Instruction:
40
- {user_input}
41
 
42
- ### Java Code:
43
- """
44
 
45
- return f"""### Instruction:
46
- Translate the following Java code to C#.
47
 
48
- ### Java Code:
49
- {user_input}
 
 
 
 
50
 
51
- ### C# Code:
52
- """
 
 
 
 
 
 
 
 
53
 
54
 
55
- def clean_output(task: str, generated_text: str) -> str:
56
- generated_text = generated_text.strip()
 
 
 
 
 
 
 
 
 
 
57
 
58
  stop_markers = [
59
  "### Instruction:",
60
- "### Java Code:",
61
- "### C# Code:",
 
 
 
 
 
62
  ]
63
 
64
  for marker in stop_markers:
65
- if marker in generated_text:
66
- generated_text = generated_text.split(marker)[0].strip()
67
-
68
- if task == "Natural Language → Java":
69
- language = "java"
70
- else:
71
- language = "csharp"
72
-
73
- return f"```{language}\n{generated_text}\n```"
74
 
 
75
 
76
- def generate_code(
77
- task: str,
78
- user_input: str,
79
- max_tokens: int,
80
- ) -> str:
81
- if not user_input or not user_input.strip():
82
- return "Please enter a description or Java code."
83
-
84
- prompt = build_prompt(task, user_input)
85
 
86
- try:
 
87
  response = llm(
88
- prompt,
89
- max_tokens=int(max_tokens),
90
  temperature=0.0,
91
  top_p=1.0,
92
- repeat_penalty=1.05,
 
93
  stop=[
 
 
 
94
  "### Instruction:",
95
- "### Java Code:",
96
- "### C# Code:",
97
  ],
98
- echo=False,
99
  )
100
 
101
- generated_text = response["choices"][0]["text"]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
102
 
103
- if not generated_text.strip():
104
- return "The model returned an empty response. Please try a more detailed input."
105
 
106
- return clean_output(task, generated_text)
107
 
108
  except Exception as error:
109
- return f"Generation failed: {error}"
 
 
 
110
 
111
 
112
- def update_placeholder(task: str):
113
  if task == "Natural Language → Java":
114
  return gr.update(
115
  label="Natural-language requirement",
@@ -126,7 +165,9 @@ def update_placeholder(task: str):
126
  "Example:\n"
127
  "public static int factorial(int n) {\n"
128
  " int result = 1;\n"
129
- " for (int i = 2; i <= n; i++) result *= i;\n"
 
 
130
  " return result;\n"
131
  "}"
132
  ),
@@ -137,11 +178,11 @@ def update_placeholder(task: str):
137
  with gr.Blocks(title="Java and C# CodeGen") as demo:
138
  gr.Markdown(
139
  """
140
- # Java and C# CodeGen
141
 
142
- Generate Java code from natural-language requirements or translate
143
- Java code into C# using a fine-tuned Qwen2.5-Coder model.
144
- """
145
  )
146
 
147
  task = gr.Dropdown(
@@ -159,15 +200,7 @@ with gr.Blocks(title="Java and C# CodeGen") as demo:
159
  "Example: Write a Java method to check whether "
160
  "a number is prime."
161
  ),
162
- lines=12,
163
- )
164
-
165
- max_tokens = gr.Slider(
166
- minimum=64,
167
- maximum=512,
168
- value=256,
169
- step=32,
170
- label="Maximum generated tokens",
171
  )
172
 
173
  generate_button = gr.Button(
@@ -175,12 +208,10 @@ with gr.Blocks(title="Java and C# CodeGen") as demo:
175
  variant="primary",
176
  )
177
 
178
- output = gr.Markdown(
179
- label="Generated code",
180
- )
181
 
182
  task.change(
183
- fn=update_placeholder,
184
  inputs=task,
185
  outputs=user_input,
186
  )
@@ -190,7 +221,6 @@ with gr.Blocks(title="Java and C# CodeGen") as demo:
190
  inputs=[
191
  task,
192
  user_input,
193
- max_tokens,
194
  ],
195
  outputs=output,
196
  )
@@ -200,12 +230,10 @@ with gr.Blocks(title="Java and C# CodeGen") as demo:
200
  [
201
  "Natural Language → Java",
202
  "Write a Java method to calculate factorial of a number using a loop.",
203
- 256,
204
  ],
205
  [
206
  "Natural Language → Java",
207
  "Write a Java method to reverse a string.",
208
- 256,
209
  ],
210
  [
211
  "Java → C#",
@@ -216,16 +244,17 @@ with gr.Blocks(title="Java and C# CodeGen") as demo:
216
  }
217
  return result;
218
  }""",
219
- 256,
220
  ],
221
  ],
222
  inputs=[
223
  task,
224
  user_input,
225
- max_tokens,
226
  ],
227
  )
228
 
229
 
230
  if __name__ == "__main__":
231
- demo.queue(max_size=10).launch()
 
 
 
 
1
  import os
2
+ import re
3
+ import threading
4
 
5
  import gradio as gr
6
  from huggingface_hub import hf_hub_download
 
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
 
 
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,
 
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",
 
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
  ),
 
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(
 
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(
 
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
  )
 
221
  inputs=[
222
  task,
223
  user_input,
 
224
  ],
225
  outputs=output,
226
  )
 
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#",
 
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()