File size: 9,143 Bytes
2160e72
 
decea45
9db926f
 
 
2160e72
 
 
f8b88f8
9db926f
38e6bca
 
 
 
 
9db926f
 
38e6bca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
decea45
 
38e6bca
 
 
 
 
9db926f
 
38e6bca
 
 
 
 
9db926f
 
 
 
 
 
 
38e6bca
9db926f
 
 
f8b88f8
 
 
 
 
 
9db926f
 
38e6bca
9db926f
 
 
f8b88f8
 
 
 
 
 
 
9db926f
 
38e6bca
9db926f
 
 
 
 
 
 
 
 
 
9331c7f
9db926f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f8b88f8
 
 
 
 
 
 
 
 
 
 
dc42699
 
 
9db926f
 
 
 
 
 
dc42699
 
 
 
 
9db926f
 
 
 
 
 
 
 
 
dc42699
 
 
 
 
 
 
 
 
 
 
 
 
9db926f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
decea45
 
1e5fd12
9db926f
f8b88f8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9db926f
 
 
 
 
 
 
 
 
 
 
1e5fd12
9db926f
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
import sys
import subprocess
from typing import List, Dict, Optional, Union, Tuple
from functools import lru_cache
from dataclasses import dataclass, field
from enum import Enum, auto
import webbrowser
import tempfile
import os
import importlib

class AppType(Enum):
    WEB_APP = auto()
    GRADIO_APP = auto()
    STREAMLIT_APP = auto()
    REACT_APP = auto()

@dataclass(frozen=True)
class Code:
    content: str
    language: str

@dataclass(frozen=True)
class Prompt:
    content: str

@dataclass(frozen=True)
class Space:
    content: str

@dataclass(frozen=True)
class Tutorial:
    content: str

@dataclass(frozen=True)
class File:
    name: str
    content: str
    language: str

@dataclass(frozen=True)
class AppInfo:
    name: str
    description: str
    features: Tuple[str, ...]
    dependencies: Tuple[str, ...]
    space: Optional[Space] = None
    tutorial: Optional[Tutorial] = None

@dataclass(frozen=True)
class App:
    code: Code

    def run(self):
        raise NotImplementedError("Subclasses must implement run method")

@dataclass(frozen=True)
class WebApp(App):
    def run(self):
        with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.html') as f:
            f.write(self.code.content)
        webbrowser.open('file://' + f.name)
        print(f"Opened WebApp in default browser. Temporary file: {f.name}")

@dataclass(frozen=True)
class GradioApp(App):
    def run(self):
        with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.py') as f:
            f.write(self.code.content)
        try:
            subprocess.run([sys.executable, f.name], check=True)
        except subprocess.CalledProcessError:
            print("Error running Gradio app. Make sure Gradio is installed: pip install gradio")
        finally:
            os.unlink(f.name)

@dataclass(frozen=True)
class StreamlitApp(App):
    def run(self):
        with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.py') as f:
            f.write(self.code.content)
        try:
            subprocess.run([sys.executable, "-m", "streamlit", "run", f.name], check=True)
        except subprocess.CalledProcessError:
            print("Error running Streamlit app. Make sure Streamlit is installed: pip install streamlit")
        finally:
            os.unlink(f.name)


@dataclass(frozen=True)
class ReactApp(App):
    def run(self):
        print("To run a React app, you need to set up a proper React environment.")
        print("Here's how you might typically run a React app:")
        print("1. Make sure you have Node.js and npm installed")
        print("2. Create a new React app: npx create-react-app my-app")
        print("3. Replace the contents of src/App.js with the generated code")
        print("4. Run the app: npm start")
        print("\nHere's the code for your App.js:")
        print(self.code.content)

class AppFactory:
    @staticmethod
    @lru_cache(maxsize=128)
    def create_prompt(app_type: AppType, app_info: AppInfo) -> Prompt:
        return Prompt(
            content=f"""
            Create a {app_type.name} web application with the following details:
            Name: {app_info.name}
            Description: {app_info.description}
            Features: {', '.join(app_info.features)}
            Dependencies: {', '.join(app_info.dependencies)}
            Space: {app_info.space.content if app_info.space else 'N/A'}
            Tutorial: {app_info.tutorial.content if app_info.tutorial else 'N/A'}
            Please generate the code for this application.
            """
        )

    @staticmethod
    @lru_cache(maxsize=128)
    def create_space(app_info: AppInfo) -> Space:
        return Space(
            content=f"""
            {app_info.name}
            {app_info.description}
            Features: {', '.join(app_info.features)}
            Dependencies: {', '.join(app_info.dependencies)}
            """
        )

    @staticmethod
    @lru_cache(maxsize=128)
    def create_app_type_prompt(app_type: AppType, app_info: AppInfo) -> Prompt:
        return Prompt(
            content=f"""
            Is the following web application a {app_type.name}?
            {app_info.name}
            {app_info.description}
            Features: {', '.join(app_info.features)}
            Dependencies: {', '.join(app_info.dependencies)}
            Please answer with either "Yes" or "No".
            """
        )

    @staticmethod
    def get_app(app_type: AppType, app_info: AppInfo) -> App:
        app_creators = {
            AppType.WEB_APP: AppFactory._create_web_app,
            AppType.GRADIO_APP: AppFactory._create_gradio_app,
            AppType.STREAMLIT_APP: AppFactory._create_streamlit_app,
            AppType.REACT_APP: AppFactory._create_react_app,
        }
        return app_creators[app_type](app_info)

    @staticmethod
    @lru_cache(maxsize=128)
    def _create_web_app(app_info: AppInfo) -> WebApp:
        code = Code(
            content=f"""
            <!DOCTYPE html>
            <html lang="en">
            <head>
                <meta charset="UTF-8">
                <meta name="viewport" content="width=device-width, initial-scale=1.0">
                <title>{app_info.name}</title>
            </head>
            <body>
                <h1>{app_info.name}</h1>
                <p>{app_info.description}</p>
            </body>
            </html>
            """,
            language="html"
        )
        return WebApp(code=code)

    @staticmethod
    @lru_cache(maxsize=128)
    def _create_gradio_app(app_info: AppInfo) -> GradioApp:
        code = Code(
            content="""
import gradio as gr

def greet(name):
    return f"Hello, {name}!"

demo = gr.Interface(greet, "text", "text")

if __name__ == "__main__":
    demo.launch()
""",
            language="python"
        )
        return GradioApp(code=code)

    @staticmethod
    @lru_cache(maxsize=128)
    def _create_streamlit_app(app_info: AppInfo) -> StreamlitApp:
        code = Code(
            content=f"""
import streamlit as st

st.title('{app_info.name}')
st.write('{app_info.description}')
""",
            language="python"
        )
        return StreamlitApp(code=code)

    @staticmethod
    @lru_cache(maxsize=128)
    def _create_react_app(app_info: AppInfo) -> ReactApp:
        code = Code(
            content=f"""
import React from 'react';

function App() {{
    return (
        <div className="App">
            <h1>{app_info.name}</h1>
            <p>{app_info.description}</p>
        </div>
    );
}}

export default App;
""",
            language="javascript"
        )
        return ReactApp(code=code)

    @staticmethod
    @lru_cache(maxsize=128)
    def parse_tutorial(app_info: AppInfo) -> Tutorial:
        return Tutorial(
            content=f"""
            ## {app_info.name} Tutorial
            **Introduction**
            {app_info.description}
            **Prerequisites**
            * Basic knowledge of web development
            * Familiarity with {', '.join(app_info.dependencies)}
            **Steps**
            {chr(10).join(f"{i+1}. {feature}" for i, feature in enumerate(app_info.features))}
            **Conclusion**
            Congratulations! You have successfully created a {app_info.name} application.
            """
        )

    @staticmethod
    def generate_files(app_type: AppType, app_info: AppInfo) -> List[File]:
        app = AppFactory.get_app(app_type, app_info)
        file_name = {
            AppType.WEB_APP: "index.html",
            AppType.GRADIO_APP: "app.py",
            AppType.STREAMLIT_APP: "app.py",
            AppType.REACT_APP: "App.js",
        }[app_type]
        return [File(name=file_name, content=app.code.content, language=app.code.language)]

    @staticmethod
    def run_app(app: App):
        app.run()

if __name__ == "__main__":
    app_info = AppInfo(
        name="My Cool App",
        description="A simple web application",
        features=("Feature 1", "Feature 2", "Feature 3"),
        dependencies=("Python", "JavaScript"),
    )
    
    # Check if required packages are installed
    required_packages = ['gradio', 'streamlit']
    missing_packages = []
    for package in required_packages:
        try:
            importlib.import_module(package)
        except ImportError:
            missing_packages.append(package)
    
    if missing_packages:
        print(f"The following packages are missing: {', '.join(missing_packages)}")
        print("Please install them using:")
        print(f"pip install {' '.join(missing_packages)}")
        sys.exit(1)

    # Create and run a WebApp
    web_app = AppFactory.get_app(AppType.WEB_APP, app_info)
    AppFactory.run_app(web_app)

    # Create and run a GradioApp
    gradio_app = AppFactory.get_app(AppType.GRADIO_APP, app_info)
    AppFactory.run_app(gradio_app)

    # Create and run a StreamlitApp
    streamlit_app = AppFactory.get_app(AppType.STREAMLIT_APP, app_info)
    AppFactory.run_app(streamlit_app)

    # Create and display info for a ReactApp
    react_app = AppFactory.get_app(AppType.REACT_APP, app_info)
    AppFactory.run_app(react_app)