LeenAnabtawe commited on
Commit
218e523
·
verified ·
1 Parent(s): 4c339c8

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +121 -0
app.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ from transformers import pipeline, AutoTokenizer
3
+
4
+ # Load the StarChat beta model
5
+ MODEL_NAME = "HuggingFaceH4/starchat-beta"
6
+ tokenizer = AutoTokenizer.from_pretrained(MODEL_NAME)
7
+ generator = pipeline(
8
+ "text-generation",
9
+ model=MODEL_NAME,
10
+ tokenizer=tokenizer,
11
+ device="cpu", # Free tier uses CPU
12
+ )
13
+
14
+ def generate_code(natural_language_input):
15
+ try:
16
+ # Create a proper prompt for the model
17
+ chat_prompt = [
18
+ {"role": "system", "content": "You are a helpful AI assistant that generates Python code based on natural language descriptions."},
19
+ {"role": "user", "content": f"Write Python code that: {natural_language_input}"}
20
+ ]
21
+
22
+ # Generate the prompt for the model
23
+ prompt = tokenizer.apply_chat_template(chat_prompt, tokenize=False, add_generation_prompt=True)
24
+
25
+ # Generate code with appropriate parameters for code generation
26
+ generated = generator(
27
+ prompt,
28
+ max_new_tokens=256,
29
+ temperature=0.2,
30
+ top_p=0.95,
31
+ do_sample=True,
32
+ pad_token_id=tokenizer.eos_token_id,
33
+ eos_token_id=tokenizer.eos_token_id,
34
+ )
35
+
36
+ # Extract and clean the generated code
37
+ full_response = generated[0]['generated_text']
38
+ code_response = full_response.replace(prompt, "").strip()
39
+
40
+ # Sometimes the model adds non-code text - we'll try to extract just the code blocks
41
+ if "```python" in code_response:
42
+ code_response = code_response.split("```python")[1].split("```")[0]
43
+ elif "```" in code_response:
44
+ code_response = code_response.split("```")[1].split("```")[0]
45
+
46
+ return code_response
47
+ except Exception as e:
48
+ return f"Error generating code: {str(e)}"
49
+
50
+ # Gradio interface
51
+ with gr.Blocks(theme=gr.themes.Soft()) as demo:
52
+ gr.Markdown("""
53
+ # 🚀 Text to Python Code Generator
54
+ ### Powered by StarChat Beta
55
+ Describe what you want the code to do in natural language, and get Python code!
56
+ """)
57
+
58
+ with gr.Row():
59
+ with gr.Column(scale=3):
60
+ input_text = gr.Textbox(
61
+ label="Describe your code task",
62
+ placeholder="e.g., 'create a Flask web server with two routes'",
63
+ lines=3,
64
+ max_lines=6
65
+ )
66
+ with gr.Row():
67
+ generate_btn = gr.Button("Generate Code", variant="primary")
68
+ clear_btn = gr.Button("Clear")
69
+
70
+ gr.Markdown("**Tips:** Be specific in your description for better results.")
71
+
72
+ with gr.Column(scale=4):
73
+ output_code = gr.Code(
74
+ label="Generated Python Code",
75
+ language="python",
76
+ interactive=True,
77
+ lines=10
78
+ )
79
+ with gr.Row():
80
+ copy_btn = gr.Button("Copy to Clipboard")
81
+ refresh_btn = gr.Button("Try Again")
82
+
83
+ # Examples
84
+ examples = gr.Examples(
85
+ examples=[
86
+ ["create a function to calculate factorial recursively"],
87
+ ["write code to download a file from URL and save it locally"],
88
+ ["create a pandas DataFrame from a dictionary and plot a bar chart"],
89
+ ["implement a simple REST API using FastAPI with GET and POST endpoints"]
90
+ ],
91
+ inputs=input_text,
92
+ label="Click any example to try it"
93
+ )
94
+
95
+ # Button actions
96
+ generate_btn.click(
97
+ fn=generate_code,
98
+ inputs=input_text,
99
+ outputs=output_code
100
+ )
101
+
102
+ clear_btn.click(
103
+ fn=lambda: ("", ""),
104
+ inputs=None,
105
+ outputs=[input_text, output_code]
106
+ )
107
+
108
+ refresh_btn.click(
109
+ fn=generate_code,
110
+ inputs=input_text,
111
+ outputs=output_code
112
+ )
113
+
114
+ copy_btn.click(
115
+ fn=lambda code: gr.Clipboard().copy(code),
116
+ inputs=output_code,
117
+ outputs=None,
118
+ api_name="copy_code"
119
+ )
120
+
121
+ demo.launch(debug=True)