Spaces:
Sleeping
Sleeping
File size: 6,911 Bytes
0b8ef98 a4cf3c5 615a9ed a4cf3c5 0b8ef98 a4cf3c5 668d0a2 a4cf3c5 615a9ed a4cf3c5 615a9ed a4cf3c5 615a9ed a4cf3c5 668d0a2 a4cf3c5 0b8ef98 a4cf3c5 35c818d a4cf3c5 35c818d a4cf3c5 615a9ed a4cf3c5 615a9ed a4cf3c5 35c818d 668d0a2 a4cf3c5 6294a96 a4cf3c5 615a9ed a4cf3c5 615a9ed a4cf3c5 35c818d a4cf3c5 35c818d a4cf3c5 668d0a2 35c818d a4cf3c5 615a9ed a4cf3c5 35c818d 0b8ef98 6294a96 668d0a2 | 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 | import streamlit as st
from transformers import pipeline
import json
from pathlib import Path
import os
class FastWebGenerator:
def __init__(self):
# Load the smallest model possible for quick text completion
self.generator = pipeline(
'text-generation',
model='distilgpt2',
device_map='auto'
)
# Load templates
self.templates = {
"react": {
"component": """
import React, { useState, useEffect } from 'react';
const {component_name} = () => {
const [data, setData] = useState([]);
useEffect(() => {
// Fetch data
fetchData();
}, []);
const fetchData = async () => {
try {
const response = await fetch('/api/data');
const jsonData = await response.json();
setData(jsonData);
} catch (error) {
console.error('Error:', error);
}
};
return (
<div className="container mx-auto p-4">
<h1 className="text-2xl font-bold mb-4">{title}</h1>
{content}
</div>
);
};
export default {component_name};
""",
"api": """
async function fetchData() {
const response = await fetch('/api/endpoint');
const data = await response.json();
return data;
}
async function postData(data) {
const response = await fetch('/api/endpoint', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
return response.json();
}
"""
},
"fastapi": {
"main": """
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
from typing import List, Optional
import uvicorn
app = FastAPI()
class ItemModel(BaseModel):
id: Optional[int]
name: str
description: Optional[str]
@app.get("/")
async def root():
return {"message": "API is running"}
@app.get("/items")
async def get_items():
return {"items": items}
@app.post("/items")
async def create_item(item: ItemModel):
items.append(item)
return item
if __name__ == "__main__":
uvicorn.run(app, host="0.0.0.0", port=8000)
""",
"crud": """
@app.get("/items/{item_id}")
async def get_item(item_id: int):
if item_id < 0 or item_id >= len(items):
raise HTTPException(status_code=404, detail="Item not found")
return items[item_id]
@app.put("/items/{item_id}")
async def update_item(item_id: int, item: ItemModel):
if item_id < 0 or item_id >= len(items):
raise HTTPException(status_code=404, detail="Item not found")
items[item_id] = item
return item
@app.delete("/items/{item_id}")
async def delete_item(item_id: int):
if item_id < 0 or item_id >= len(items):
raise HTTPException(status_code=404, detail="Item not found")
item = items.pop(item_id)
return item
"""
},
"mongodb": """
from motor.motor_asyncio import AsyncIOMotorClient
client = AsyncIOMotorClient('mongodb://localhost:27017')
db = client.database_name
async def get_all():
cursor = db.collection.find({})
return await cursor.to_list(length=100)
async def get_one(id: str):
return await db.collection.find_one({"_id": id})
async def create_one(data: dict):
result = await db.collection.insert_one(data)
return result.inserted_id
async def update_one(id: str, data: dict):
result = await db.collection.update_one(
{"_id": id},
{"$set": data}
)
return result.modified_count
async def delete_one(id: str):
result = await db.collection.delete_one({"_id": id})
return result.deleted_count
"""
}
def customize_code(self, template, params):
# Quick text customization using the model
prompt = f"Customize this code: {template}\nWith these parameters: {params}\n"
result = self.generator(prompt, max_length=100, num_return_sequences=1)[0]['generated_text']
return result
def generate_project(self, specs):
frontend_code = self.templates["react"]["component"].replace(
"{component_name}", specs["component_name"]
).replace(
"{title}", specs["title"]
).replace(
"{content}", specs["content"]
)
backend_code = self.templates["fastapi"]["main"]
if specs.get("crud", False):
backend_code += self.templates["fastapi"]["crud"]
db_code = self.templates["mongodb"] if specs["database"] == "MongoDB" else ""
return {
"frontend": frontend_code,
"backend": backend_code,
"database": db_code
}
def main():
st.set_page_config(page_title="Fast Code Generator", layout="wide")
if 'generator' not in st.session_state:
with st.spinner("Loading generator..."):
st.session_state.generator = FastWebGenerator()
st.title("⚡ Fast Code Generator")
with st.form("generate_form"):
col1, col2 = st.columns(2)
with col1:
component_name = st.text_input("Component Name", "MyComponent")
title = st.text_input("Title", "My App")
content = st.text_area("Content", "<p>Your content here</p>")
with col2:
database = st.selectbox("Database", ["MongoDB", "PostgreSQL"])
add_crud = st.checkbox("Add CRUD Operations", value=True)
add_auth = st.checkbox("Add Authentication", value=False)
if st.form_submit_button("Generate"):
specs = {
"component_name": component_name,
"title": title,
"content": content,
"database": database,
"crud": add_crud,
"auth": add_auth
}
result = st.session_state.generator.generate_project(specs)
# Display results
tabs = st.tabs(["Frontend", "Backend", "Database"])
with tabs[0]:
st.code(result["frontend"], language="javascript")
with tabs[1]:
st.code(result["backend"], language="python")
with tabs[2]:
st.code(result["database"], language="python")
# Add download button
combined_code = f"""
// Frontend Code
{result['frontend']}
// Backend Code
{result['backend']}
// Database Code
{result['database']}
"""
st.download_button(
"Download Code",
combined_code,
file_name="generated_code.txt",
mime="text/plain"
)
if __name__ == "__main__":
main() |