Cristobal299 commited on
Commit
20ef2f4
·
verified ·
1 Parent(s): f3c0f06

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +56 -0
app.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # -*- coding: utf-8 -*-
2
+ import os
3
+ import gradio as gr
4
+ import openai
5
+
6
+ # Load OpenAI API key from environment
7
+ openai_api_key = os.environ.get("OPENAI_API_KEY")
8
+ if openai_api_key is None:
9
+ raise ValueError("OPENAI_API_KEY environment variable not set")
10
+ openai.api_key = openai_api_key
11
+
12
+ def improve_code(user_code, language):
13
+ """
14
+ Sends the user code to OpenAI GPT model and asks for an improved version.
15
+ """
16
+ system_prompt = f"You are an expert {language} developer. Refactor and improve the following code. Keep the same functionality but make it cleaner, more efficient and well commented."
17
+ messages = [
18
+ {"role": "system", "content": system_prompt},
19
+ {"role": "user", "content": user_code}
20
+ ]
21
+ try:
22
+ response = openai.ChatCompletion.create(
23
+ model="gpt-3.5-turbo",
24
+ messages=messages,
25
+ temperature=0.2,
26
+ max_tokens=1024,
27
+ n=1,
28
+ stop=None,
29
+ )
30
+ improved = response.choices[0].message.content.strip()
31
+ return improved
32
+ except Exception as e:
33
+ return f"Error: {str(e)}"
34
+
35
+ # Build Gradio interface
36
+ with gr.Blocks() as demo:
37
+ gr.Markdown("# Code Improver")
38
+ gr.Markdown("Enter your code and select the programming language. The model will return a cleaner version.")
39
+ with gr.Row():
40
+ code_input = gr.Textbox(label="Original Code", lines=15, placeholder="Paste your code here")
41
+ language_dropdown = gr.Dropdown(
42
+ choices=["Python", "JavaScript", "Java", "C++", "C#", "Go", "Ruby", "PHP"],
43
+ value="Python",
44
+ label="Language"
45
+ )
46
+ improve_button = gr.Button("Improve")
47
+ output_box = gr.Textbox(label="Improved Code", lines=15)
48
+
49
+ improve_button.click(
50
+ fn=improve_code,
51
+ inputs=[code_input, language_dropdown],
52
+ outputs=output_box
53
+ )
54
+
55
+ if __name__ == "__main__":
56
+ demo.launch()