acecalisto3 commited on
Commit
9db926f
1 Parent(s): ccbdeab

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +229 -152
app.py CHANGED
@@ -1,154 +1,231 @@
1
- from huggingface_hub import InferenceClient
2
- import gradio as gr
3
- import random
4
- import prompts
5
-
6
- client = InferenceClient("mistralai/Mixtral-8x7B-Instruct-v0.1")
7
-
8
- def format_prompt(message, history):
9
- prompt = "<s>"
10
- for user_prompt, bot_response in history:
11
- prompt += f"[INST] {user_prompt} [/INST]"
12
- prompt += f" {bot_response}</s> "
13
- prompt += f"[INST] {message} [/INST]"
14
- return prompt
15
-
16
- agents = [
17
- "WEB_DEV",
18
- "AI_SYSTEM_PROMPT",
19
- "PYTHON_CODE_DEV",
20
- "CODE_REVIEW_ASSISTANT",
21
- "CONTENT_WRITER_EDITOR",
22
- "QUESTION_GENERATOR",
23
- "HUGGINGFACE_FILE_DEV",
24
- ]
25
-
26
- def generate(
27
- prompt, history, agent_name=agents[0], sys_prompt="", temperature=0.9, max_new_tokens=256, top_p=0.95, repetition_penalty=1.0,
28
- ):
29
- seed = random.randint(1, 1111111111111111)
30
-
31
- agent = prompts.WEB_DEV
32
- if agent_name == "WEB_DEV":
33
- agent = prompts.WEB_DEV_SYSTEM_PROMPT
34
- elif agent_name == "CODE_REVIEW_ASSISTANT":
35
- agent = prompts.CODE_REVIEW_ASSISTANT
36
- elif agent_name == "CONTENT_WRITER_EDITOR":
37
- agent = prompts.CONTENT_WRITER_EDITOR
38
- elif agent_name == "SOCIAL_MEDIA_MANAGER":
39
- agent = prompts.SOCIAL_MEDIA_MANAGER
40
- elif agent_name == "AI_SYSTEM_PROMPT":
41
- agent = prompts.AI_SYSTEM_PROMPT
42
- elif agent_name == "PYTHON_CODE_DEV":
43
- agent = prompts.PYTHON_CODE_DEV
44
- elif agent_name == "QUESTION_GENERATOR":
45
- agent = prompts.QUESTION_GENERATOR
46
- elif agent_name == "HUGGINGFACE_FILE_DEV":
47
- agent = prompts.HUGGINGFACE_FILE_DEV
48
-
49
- system_prompt = agent
50
- temperature = float(temperature)
51
- if temperature < 1e-2:
52
- temperature = 1e-2
53
- top_p = float(top_p)
54
-
55
- generate_kwargs = dict(
56
- temperature=temperature,
57
- max_new_tokens=max_new_tokens,
58
- top_p=top_p,
59
- repetition_penalty=repetition_penalty,
60
- do_sample=True,
61
- seed=seed,
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
  )
 
 
 
 
 
 
 
 
 
 
 
 
63
 
64
- formatted_prompt = format_prompt(f"{system_prompt}, {prompt}", history)
65
- stream = client.text_generation(formatted_prompt, **generate_kwargs, stream=True, details=True, return_full_text=False)
66
- output = ""
67
-
68
- for response in stream:
69
- output += response.token.text
70
- yield output
71
- return output
72
-
73
- additional_inputs = [
74
- gr.Dropdown(
75
- label="Agents",
76
- choices=[s for s in agents],
77
- value=agents[0],
78
- interactive=True,
79
- ),
80
- gr.Textbox(
81
- label="System Prompt",
82
- max_lines=1,
83
- interactive=True,
84
- ),
85
- gr.Slider(
86
- label="Temperature",
87
- value=0.9,
88
- minimum=0.0,
89
- maximum=1.0,
90
- step=0.05,
91
- interactive=True,
92
- info="Higher values produce more diverse outputs",
93
- ),
94
- gr.Slider(
95
- label="Max new tokens",
96
- value=1048 * 10,
97
- minimum=0,
98
- maximum=1048 * 10,
99
- step=64,
100
- interactive=True,
101
- info="The maximum numbers of new tokens",
102
- ),
103
- gr.Slider(
104
- label="Top-p (nucleus sampling)",
105
- value=0.90,
106
- minimum=0.0,
107
- maximum=1,
108
- step=0.05,
109
- interactive=True,
110
- info="Higher values sample more low-probability tokens",
111
- ),
112
- gr.Slider(
113
- label="Repetition penalty",
114
- value=1.2,
115
- minimum=1.0,
116
- maximum=2.0,
117
- step=0.05,
118
- interactive=True,
119
- info="Penalize repeated tokens",
120
- ),
121
- ]
122
-
123
- examples = [
124
- ["Create a simple web application using Flask", agents[0], None, None, None, None],
125
- ["Generate a Python script to perform a linear regression analysis", agents[2], None, None, None, None],
126
- ["Create a Dockerfile for a Node.js application", agents[1], None, None, None, None],
127
- ["Write a shell script to automate the deployment of a web application to a server", agents[3], None, None, None, None],
128
- ["Generate a SQL query to retrieve the top 10 most popular products by sales", agents[4], None, None, None, None],
129
- ["Write a Python script to generate a random password with a given length and complexity", agents[2], None, None, None, None],
130
- ["Create a simple game in Unity using C#", agents[0], None, None, None, None],
131
- ["Generate a Java program to implement a binary search algorithm", agents[2], None, None, None, None],
132
- ["Write a shell script to monitor the CPU usage of a server", agents[1], None, None, None, None],
133
- ["Create a simple web application using React and Node.js", agents[0], None, None, None, None],
134
- ["Generate a Python script to perform a sentiment analysis on a given text", agents[2], None, None, None, None],
135
- ["Write a shell script to automate the backup of a MySQL database", agents[1], None, None, None, None],
136
- ["Create a simple game in Unreal Engine using C++", agents[3], None, None, None, None],
137
- ["Generate a Java program to implement a bubble sort algorithm", agents[2], None, None, None, None],
138
- ["Write a shell script to monitor the memory usage of a server", agents[1], None, None, None, None],
139
- ["Create a simple web application using Angular and Node.js", agents[0], None, None, None, None],
140
- ["Generate a Python script to perform a text classification on a given dataset", agents[2], None, None, None, None],
141
- ["Write a shell script to automate the installation of a software package on a server", agents[1], None, None, None, None],
142
- ["Create a simple game in Godot using GDScript", agents[3], None, None, None, None],
143
- ["Generate a Java program to implement a merge sort algorithm", agents[2], None, None, None, None],
144
- ["Write a shell script to automate the cleanup of temporary files on a server", agents[1], None, None, None, None],
145
- ]
146
-
147
- gr.ChatInterface(
148
- fn=generate,
149
- chatbot=gr.Chatbot(show_label=False, show_share_button=False, show_copy_button=True, likeable=True, layout="panel"),
150
- additional_inputs=additional_inputs,
151
- title="Mixtral 46.7B",
152
- examples=examples,
153
- concurrency_limit=20,
154
- ).launch(show_api=False)
 
1
+ from typing import List, Dict, Optional, Union
2
+ from functools import lru_cache
3
+ from dataclasses import dataclass, field
4
+ from enum import Enum, auto
5
+
6
+
7
+
8
+ @dataclass(frozen=True)
9
+ class WebApp:
10
+ code: Code
11
+
12
+ def run(self):
13
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.html') as f:
14
+ f.write(self.code.content)
15
+ webbrowser.open('file://' + f.name)
16
+ print(f"Opened WebApp in default browser. Temporary file: {f.name}")
17
+
18
+ @dataclass(frozen=True)
19
+ class GradioApp:
20
+ code: Code
21
+
22
+ def run(self):
23
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.py') as f:
24
+ f.write(self.code.content)
25
+ subprocess.run([sys.executable, f.name])
26
+ os.unlink(f.name)
27
+
28
+ @dataclass(frozen=True)
29
+ class StreamlitApp:
30
+ code: Code
31
+
32
+ def run(self):
33
+ with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.py') as f:
34
+ f.write(self.code.content)
35
+ subprocess.run([sys.executable, "-m", "streamlit", "run", f.name])
36
+ os.unlink(f.name)
37
+
38
+ @dataclass(frozen=True)
39
+ class ReactApp:
40
+ code: Code
41
+
42
+ def run(self):
43
+ print("To run a React app, you need to set up a proper React environment.")
44
+ print("Here's how you might typically run a React app:")
45
+ print("1. Make sure you have Node.js and npm installed")
46
+ print("2. Create a new React app: npx create-react-app my-app")
47
+ print("3. Replace the contents of src/App.js with the generated code")
48
+ print("4. Run the app: npm start")
49
+ print("\nHere's the code for your App.js:")
50
+ print(self.code.content)
51
+
52
+ class AppFactory:
53
+ @staticmethod
54
+ @lru_cache(maxsize=128)
55
+ def create_prompt(app_type: AppType, app_info: AppInfo) -> Prompt:
56
+ return Prompt(
57
+ content=f"""
58
+ Create a {app_type.name} web application with the following details:
59
+ Name: {app_info.name}
60
+ Description: {app_info.description}
61
+ Features: {', '.join(app_info.features)}
62
+ Dependencies: {', '.join(app_info.dependencies)}
63
+ Space: {app_info.space.content if app_info.space else 'N/A'}
64
+ Tutorial: {app_info.tutorial.content if app_info.tutorial else 'N/A'}
65
+ Please generate the code for this application.
66
+ """
67
+ )
68
+
69
+ @staticmethod
70
+ @lru_cache(maxsize=128)
71
+ def create_space(app_info: AppInfo) -> Space:
72
+ return Space(
73
+ content=f"""
74
+ {app_info.name}
75
+ {app_info.description}
76
+ Features: {', '.join(app_info.features)}
77
+ Dependencies: {', '.join(app_info.dependencies)}
78
+ """
79
+ )
80
+
81
+ @staticmethod
82
+ @lru_cache(maxsize=128)
83
+ def create_app_type_prompt(app_type: AppType, app_info: AppInfo) -> Prompt:
84
+ return Prompt(
85
+ content=f"""
86
+ Is the following web application a {app_type.name}?
87
+ {app_info.name}
88
+ {app_info.description}
89
+ Features: {', '.join(app_info.features)}
90
+ Dependencies: {', '.join(app_info.dependencies)}
91
+ Please answer with either "Yes" or "No".
92
+ """
93
+ )
94
+
95
+ @staticmethod
96
+ def get_app(app_type: AppType, app_info: AppInfo) -> App:
97
+ app_creators = {
98
+ AppType.WEB_APP: AppFactory._create_web_app,
99
+ AppType.GRADIO_APP: AppFactory._create_gradio_app,
100
+ AppType.STREAMLIT_APP: AppFactory._create_streamlit_app,
101
+ AppType.REACT_APP: AppFactory._create_react_app,
102
+ }
103
+ return app_creators[app_type](app_info)
104
+
105
+ @staticmethod
106
+ @lru_cache(maxsize=128)
107
+ def _create_web_app(app_info: AppInfo) -> WebApp:
108
+ code = Code(
109
+ content=f"""
110
+ <!DOCTYPE html>
111
+ <html lang="en">
112
+ <head>
113
+ <meta charset="UTF-8">
114
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
115
+ <title>{app_info.name}</title>
116
+ </head>
117
+ <body>
118
+ <h1>{app_info.name}</h1>
119
+ <p>{app_info.description}</p>
120
+ </body>
121
+ </html>
122
+ """,
123
+ language="html"
124
+ )
125
+ return WebApp(code=code)
126
+
127
+ @staticmethod
128
+ @lru_cache(maxsize=128)
129
+ def _create_gradio_app(app_info: AppInfo) -> GradioApp:
130
+ code = Code(
131
+ content=f"""
132
+ import gradio as gr
133
+ def greet(name):
134
+ return f"Hello, {{name}}!"
135
+ demo = gr.Interface(greet, "text", "text")
136
+ if __name__ == "__main__":
137
+ demo.launch()
138
+ """,
139
+ language="python"
140
+ )
141
+ return GradioApp(code=code)
142
+
143
+ @staticmethod
144
+ @lru_cache(maxsize=128)
145
+ def _create_streamlit_app(app_info: AppInfo) -> StreamlitApp:
146
+ code = Code(
147
+ content=f"""
148
+ import streamlit as st
149
+ st.title('{app_info.name}')
150
+ st.write('{app_info.description}')
151
+ """,
152
+ language="python"
153
+ )
154
+ return StreamlitApp(code=code)
155
+
156
+ @staticmethod
157
+ @lru_cache(maxsize=128)
158
+ def _create_react_app(app_info: AppInfo) -> ReactApp:
159
+ code = Code(
160
+ content=f"""
161
+ import React from 'react';
162
+ function App() {{
163
+ return (
164
+ <div className="App">
165
+ <h1>{app_info.name}</h1>
166
+ <p>{app_info.description}</p>
167
+ </div>
168
+ );
169
+ }}
170
+ export default App;
171
+ """,
172
+ language="javascript"
173
+ )
174
+ return ReactApp(code=code)
175
+
176
+ @staticmethod
177
+ @lru_cache(maxsize=128)
178
+ def parse_tutorial(app_info: AppInfo) -> Tutorial:
179
+ return Tutorial(
180
+ content=f"""
181
+ ## {app_info.name} Tutorial
182
+ **Introduction**
183
+ {app_info.description}
184
+ **Prerequisites**
185
+ * Basic knowledge of web development
186
+ * Familiarity with {', '.join(app_info.dependencies)}
187
+ **Steps**
188
+ {chr(10).join(f"{i+1}. {feature}" for i, feature in enumerate(app_info.features))}
189
+ **Conclusion**
190
+ Congratulations! You have successfully created a {app_info.name} application.
191
+ """
192
+ )
193
+
194
+ @staticmethod
195
+ def generate_files(app_type: AppType, app_info: AppInfo) -> List[File]:
196
+ app = AppFactory.get_app(app_type, app_info)
197
+ file_name = {
198
+ AppType.WEB_APP: "index.html",
199
+ AppType.GRADIO_APP: "app.py",
200
+ AppType.STREAMLIT_APP: "app.py",
201
+ AppType.REACT_APP: "App.js",
202
+ }[app_type]
203
+ return [File(name=file_name, content=app.code.content, language=app.code.language)]
204
+
205
+ @staticmethod
206
+ def run_app(app: App):
207
+ app.run()
208
+
209
+ if __name__ == "__main__":
210
+ app_info = AppInfo(
211
+ name="My Cool App",
212
+ description="A simple web application",
213
+ features=["Feature 1", "Feature 2", "Feature 3"],
214
+ dependencies=["Python", "JavaScript"],
215
  )
216
+
217
+ # Create and run a WebApp
218
+ web_app = AppFactory.get_app(AppType.WEB_APP, app_info)
219
+ AppFactory.run_app(web_app)
220
+
221
+ # Create and run a GradioApp
222
+ gradio_app = AppFactory.get_app(AppType.GRADIO_APP, app_info)
223
+ AppFactory.run_app(gradio_app)
224
+
225
+ # Create and run a StreamlitApp
226
+ streamlit_app = AppFactory.get_app(AppType.STREAMLIT_APP, app_info)
227
+ AppFactory.run_app(streamlit_app)
228
 
229
+ # Create and display info for a ReactApp
230
+ react_app = AppFactory.get_app(AppType.REACT_APP, app_info)
231
+ AppFactory.run_app(react_app)