SeifElden2342532 commited on
Commit
e68b4e3
·
verified ·
1 Parent(s): c141a00

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +61 -21
app.py CHANGED
@@ -1,23 +1,63 @@
1
  import gradio as gr
 
 
 
2
 
3
- # The URL of your deployed Modal app
4
- MODAL_URL = "https://seifosama708--code-optimizer-app-web.modal.run"
5
-
6
- # Using an iframe to embed the Modal app directly
7
- # This is the most reliable way to display an external web server in a Space
8
- with gr.Blocks(fill_height=True) as demo:
9
- gr.HTML(
10
- f"""
11
- <iframe
12
- src="{MODAL_URL}"
13
- width="100%"
14
- height="100%"
15
- style="border:none; min-height:800px;"
16
- allow="accelerometer; ambient-light-sensor; camera; encrypted-media; geolocation; gyroscope; hid; microphone; midi; payment; usb; vr; xr-spatial-tracking"
17
- sandbox="allow-forms allow-modals allow-popups allow-popups-to-escape-sandbox allow-same-origin allow-scripts allow-downloads"
18
- ></iframe>
19
- """
20
- )
21
-
22
- if __name__ == "__main__":
23
- demo.launch()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  import gradio as gr
2
+ import torch
3
+ from transformers import AutoTokenizer, AutoModelForCausalLM
4
+ from peft import PeftModel
5
 
6
+ base_model_id = "Qwen/Qwen2.5-Coder-7B-Instruct"
7
+ adapter_repo_id = "SeifElden2342532/Code-Optimizer"
8
+
9
+ print("Loading model...")
10
+ tokenizer = AutoTokenizer.from_pretrained(base_model_id)
11
+ model = AutoModelForCausalLM.from_pretrained(
12
+ base_model_id,
13
+ torch_dtype=torch.bfloat16,
14
+ device_map="auto"
15
+ )
16
+ model = PeftModel.from_pretrained(model, adapter_repo_id)
17
+ model = model.merge_and_unload()
18
+ model.eval()
19
+ print("Model ready!")
20
+
21
+ SYSTEM_PROMPT = "You are an expert Python code optimizer. Your goal is to take user-provided Python code and optimize it for performance, readability, or conciseness, based on the user's specified category. Provide the optimized code, a brief explanation of the changes, and a complexity comparison table (e.g., time and space complexity before and after optimization)."
22
+
23
+ def optimize(code, category):
24
+ if not code.strip():
25
+ return "Please enter some Python code."
26
+
27
+ messages = [
28
+ {"role": "system", "content": SYSTEM_PROMPT},
29
+ {"role": "user", "content": f"Original Code:\n```python\n{code}\n```\nCategory: {category}"}
30
+ ]
31
+
32
+ text = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
33
+ model_inputs = tokenizer([text], return_tensors="pt").to(model.device)
34
+
35
+ with torch.no_grad():
36
+ generated_ids = model.generate(**model_inputs, max_new_tokens=1024)
37
+
38
+ # Strip input tokens from output
39
+ input_len = model_inputs["input_ids"].shape[1]
40
+ output_ids = generated_ids[0][input_len:]
41
+ return tokenizer.decode(output_ids, skip_special_tokens=True)
42
+
43
+ demo = gr.Interface(
44
+ fn=optimize,
45
+ inputs=[
46
+ gr.Code(language="python", label="Your Python Code", lines=15),
47
+ gr.Radio(
48
+ choices=["Performance", "Readability", "Conciseness"],
49
+ value="Performance",
50
+ label="Optimization Category"
51
+ )
52
+ ],
53
+ outputs=gr.Textbox(label="Optimized Code & Explanation", lines=20),
54
+ title="⚡ Python Code Optimizer",
55
+ description="A QLoRA fine-tuned Qwen2.5-Coder-7B model that optimizes your Python code for performance, readability, or conciseness.",
56
+ examples=[
57
+ ["def factorial(n):\n if n == 0:\n return 1\n else:\n return n * factorial(n-1)", "Performance"],
58
+ ["result = []\nfor i in range(10):\n result.append(i * 2)", "Conciseness"],
59
+ ],
60
+ flagging_mode="never"
61
+ )
62
+
63
+ demo.launch()