ComfyUI Workflow
Error: Invalid JSON format
```comfyui
=== Dockerfile ===
FROM python:3.11-slim
WORKDIR /app
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
EXPOSE 8000
CMD ["python", "main.py"]
=== requirements.txt ===
fastapi==0.109.0
uvicorn==0.27.0
python-multipart==0.0.6
jinja2==3.1.3
pydantic==2.5.3
httpx==0.26.0
=== package.json ===
{
"name": "python-code-generator",
"version": "1.0.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint"
},
"dependencies": {
"next": "14.1.0",
"react": "^18",
"react-dom": "^18",
"lucide-react": "^0.292.0",
"clsx": "^2.0.0",
"tailwind-merge": "^2.0.0",
"prismjs": "^1.29.0",
"react-syntax-highlighter": "^11.0.0"
},
"devDependencies": {
"autoprefixer": "^10.0.1",
"postcss": "^8",
"tailwindcss": "^3.3.0"
}
}
=== next.config.js ===
/** @type {import('next').NextConfig} */
const nextConfig = {
reactStrictMode: true,
api: {
bodyParser: true,
}
}
module.exports = nextConfig
=== postcss.config.js ===
module.exports = {
plugins: {
tailwindcss: {},
autoprefixer: {},
},
}
=== tailwind.config.js ===
/** @type {import('tailwindcss').Config} */
module.exports = {
content: [
'./pages/**/*.{js,ts,jsx,tsx}',
'./components/**/*.{js,ts,jsx,tsx}',
],
theme: {
extend: {
colors: {
python: {
blue: '#3776AB',
yellow: '#FFD43B',
dark: '#306998',
light: '#FFE873',
}
}
},
},
plugins: [],
}
=== pages/_app.js ===
import '../styles/globals.css'
export default function App({ Component, pageProps }) {
return
}
=== styles/globals.css ===
@tailwind base;
@tailwind components;
@tailwind utilities;
body {
background-color: #f0f4f8;
color: #1e293b;
}
.code-block {
background: #1e1e1e;
border-radius: 8px;
padding: 16px;
font-family: 'Courier New', monospace;
overflow-x: auto;
}
=== pages/index.js ===
import { useState, useEffect } from 'react';
import Header from '../components/Header';
import Sidebar from '../components/Sidebar';
import CodeList from '../components/CodeList';
import CodeDisplay from '../components/CodeDisplay';
import { Code, Play, Download, Copy, CheckCircle2, AlertCircle, Sparkles } from 'lucide-react';
const MOCK_CODES = [
{ id: '1', title: 'FastAPI Hello World', code: 'from fastapi import FastAPI\n\napp = FastAPI()\n\n@app.get("/")\nasync def root():\n return {"message": "Hello World"}\n\nif __name__ == "__main__":\n import uvicorn\n uvicorn.run(app, host="0.0.0.0", port=8000)', date: '10:45 AM', language: 'Python', complexity: 'simple' },
{ id: '2', title: 'Data Processing Script', code: 'import pandas as pd\nimport numpy as np\n\ndef process_data(file_path):\n df = pd.read_csv(file_path)\n df["processed"] = df["value"] * 2\n return df\n\nif __name__ == "__main__":\n result = process_data("data.csv")\n print(result.head())', date: 'Yesterday', language: 'Python', complexity: 'medium' },
{ id: '3', title: 'Web Scraper with BeautifulSoup', code: 'import requests\nfrom bs4 import BeautifulSoup\n\ndef scrape_website(url):\n response = requests.get(url)\n soup = BeautifulSoup(response.text, "html.parser")\n title = soup.find("title").text\n return title\n\nif __name__ == "__main__":\n print(scrape_website("https://example.com"))', date: 'Oct 24', language: 'Python', complexity: 'medium' },
{ id: '4', title: 'Machine Learning Model', code: 'from sklearn.linear_model import LinearRegression\nimport numpy as np\n\nX = np.array([[1], [2], [3], [4]])\ny = np.array([2, 4, 6, 8])\n\nmodel = LinearRegression()\nmodel.fit(X, y)\n\nprint(f"Coefficient: {model.coef_}")\nprint(f"Intercept: {model.intercept_}")', date: 'Oct 23', language: 'Python', complexity: 'complex' },
{ id: '5', title: 'File Utility Functions', code: 'import os\nimport json\n\ndef read_json(file_path):\n with open(file_path, "r") as f:\n return json.load(f)\n\ndef write_json(file_path, data):\n with open(file_path, "w") as f:\n json.dump(data, f, indent=4)\n\nif __name__ == "__main__":\n data = read_json("config.json")\n write_json("output.json", data)', date: 'Oct 22', language: 'Python', complexity: 'simple' },
];
export default function Home() {
const [codes, setCodes] = useState(MOCK_CODES);
const [selectedId, setSelectedId] = useState(null);
const [searchQuery, setSearchQuery] = useState('');
const [activeFilter, setActiveFilter] = useState('All');
const [notification, setNotification] = useState(null);
const [prompt, setPrompt] = useState('');
const [isGenerating, setIsGenerating] = useState(false);
const filteredCodes = codes.filter(code => {
const matchesSearch = code.title.toLowerCase().includes(searchQuery.toLowerCase()) ||
code.code.toLowerCase().includes(searchQuery.toLowerCase());
const matchesFilter = activeFilter === 'All' || code.complexity === activeFilter;
return matchesSearch && matchesFilter;
});
const generateCode = async () => {
if (!prompt.trim()) return;
setIsGenerating(true);
try {
const response = await fetch('/api/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ prompt: prompt }),
});
const data = await response.json();
const newCode = {
id: String(Date.now()),
title: prompt.substring(0, 30) + '...',
code: data.code || '# Generated code placeholder',
date: 'Now',
language: 'Python',
complexity: 'medium'
};
setCodes(prev => [newCode, ...prev]);
setSelectedId(newCode.id);
setPrompt('');
setNotification({ type: 'success', message: 'Code generated successfully!' });
} catch (error) {
setNotification({ type: 'error', message: 'Failed to generate code' });
}
setIsGenerating(false);
setTimeout(() => setNotification(null), 3000);
};
const copyCode = (code) => {
navigator.clipboard.writeText(code);
setNotification({ type: 'success', message: 'Code copied to clipboard!' });
setTimeout(() => setNotification(null), 3000);
};
const downloadCode = (code, title) => {
const blob = new Blob([code], { type: 'text/plain' });
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = `${title.replace(/\s+/g, '_').toLowerCase()}.py`;
link.click();
URL.closeObjectURL(url);
setNotification({ type: 'success', message: 'Code downloaded!' });
setTimeout(() => setNotification(null), 3000);
};
const deleteCode = (id) => {
setCodes(prev => prev.filter(c => c.id !== id));
if (selectedId === id) setSelectedId(null);
setNotification({ type: 'success', message: 'Code deleted' });
setTimeout(() => setNotification(null), 3000);
};
const selectedCode = codes.find(c => c.id === selectedId);
return (
{selectedCode ? (
deleteCode(selectedCode.id)}
onCopy={() => copyCode(selectedCode.code)}
onDownload={() => downloadCode(selectedCode.code, selectedCode.title)}
/>
) : (
No code selected
Select a code snippet from the list or generate new Python code using the prompt below.
)}
{notification && (
{notification.type === 'success' ?
:
}
{notification.message}
)}
);
}
=== components/Header.js ===
import { Search, Menu, Settings, HelpCircle, Grid, Code } from 'lucide-react';
export default function Header({ searchQuery, setSearchQuery }) {
return (
);
}
=== components/Sidebar.js ===
import { Code, Star, Clock, Book, FileCode, Archive, Trash2, Tag } from 'lucide-react';
export default function Sidebar({ activeFilter, setActiveFilter }) {
const menuItems = [
{ id: 'All', icon: Code, label: 'All Code', count: 12 },
{ id: 'Starred', icon: Star, label: 'Starred', count: 3 },
{ id: 'Recent', icon: Clock, label: 'Recent', count: 5 },
{ id: 'Templates', icon: Book, label: 'Templates', count: 8 },
{ id: 'Drafts', icon: FileCode, label: 'Drafts', count: 2 },
];
const labels = [
{ id: 'simple', icon: Tag, color: 'bg-green-500', label: 'Simple' },
{ id: 'medium', icon: Tag, color: 'bg-yellow-500', label: 'Medium' },
{ id: 'complex', icon: Tag, color: 'bg-red-500', label: 'Complex' },
];
return (
);
}
=== components/CodeList.js ===
import { Star, Archive, Trash2, Code } from 'lucide-react';
export default function CodeList({ codes, selectedId, setSelectedId }) {
return (
{codes.length === 0 ? (
No code snippets found matching your search.
) : (
codes.map((code) => (
setSelectedId(code.id)}
className={`group relative p-4 border-b border-slate-100 cursor-pointer transition-all ${
selectedId === code.id
? 'bg-blue-50 border-l-4 border-l-python-blue'
: 'hover:bg-slate-50 border-l-4 border-l-transparent'
}`}
>
{code.title}
{code.date}
{code.language} ยท {code.complexity}
{code.code.substring(0, 50)}...
))
)}
);
}
=== components/CodeDisplay.js ===
import { Copy, Download, Trash2, Archive, MoreVertical, Star, Play, Code } from 'lucide-react';
export default function CodeDisplay({ code, onDelete, onCopy, onDownload }) {
return (
{/* Toolbar */}
{code.language}
{code.complexity}
{/* Code Content */}
{code.title}
Generated Code
Created {code.date}
{/* Action Buttons */}
);
}
=== pages/api/generate.py ===
from fastapi import FastAPI
from pydantic import BaseModel
import json
app = FastAPI()
class GenerateRequest(BaseModel):
prompt: str
@app.post("/api/generate")
async def generate_code(request: GenerateRequest):
# This is a mock implementation
# In production, this would call an AI code generation API
prompt = request.prompt.lower()
if "hello" in prompt or "world" in prompt:
code = '''from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)'''
elif "fibonacci" in prompt or "fib" in prompt:
code = '''def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
# Generate first 10 fibonacci numbers
for i in range(10):
print(f"F({i}) = {fibonacci(i)}")'''
elif "file" in prompt or "read" in prompt:
code = '''def read_file(file_path):
with open(file_path, "r") as f:
content = f.read()
return content
def write_file(file_path, content):
with open(file_path, "w") as f:
f.write(content)
if __name__ == "__main__":
text = read_file("input.txt")
write_file("output.txt", text.upper())'''
else:
code = f'''# Generated code for: {request.prompt}
def generated_function():
"""
This function was generated based on your prompt.
Customize it to fit your needs.
"""
print("Hello from generated code!")
return True
if __name__ == "__main__":
result = generated_function()
print(f"Result: {result}")'''
return {"code": code, "prompt": request.prompt}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
=== pages/api/generate.js ===
export default async function handler(req, res) {
if (req.method === 'POST') {
const { prompt } = req.body;
// Mock code generation logic
let code = '';
if (prompt.toLowerCase().includes('hello') || prompt.toLowerCase().includes('world')) {
code = `from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)`;
} else if (prompt.toLowerCase().includes('fibonacci') || prompt.toLowerCase().includes('fib')) {
code = `def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
# Generate first 10 fibonacci numbers
for i in range(10):
print(f"F({i}) = {fibonacci(i)})`;
} else {
code = `# Generated code for: ${prompt}
def generated_function():
"""
This function was generated based on your prompt.
Customize it to fit your needs.
"""
print("Hello from generated code!")
return True
if __name__ == "__main__":
result = generated_function()
print(f"Result: {result}")`;
}
res.status(200).json({ code, prompt });
} else {
res.status(405).json({ error: 'Method not allowed' });
}
}
=== main.py ===
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import FileResponse
import os
app = FastAPI()
# Serve static files from Next.js build
app.mount("/_next", StaticFiles(directory=".next/static", html=True), name="next_static")
app.mount("/static", StaticFiles(directory="public", html=True), name="static")
@app.get("/")
async def root():
return FileResponse("public/index.html")
@app.post("/api/generate")
async def generate_code(request: dict):
prompt = request.get("prompt", "")
# Mock code generation logic
if "hello" in prompt.lower() or "world" in prompt.lower():
code = '''from fastapi import FastAPI
app = FastAPI()
@app.get("/")
async def root():
return {"message": "Hello World"}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)'''
elif "fibonacci" in prompt.lower() or "fib" in prompt.lower():
code = '''def fibonacci(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
for i in range(10):
print(f"F({i}) = {fibonacci(i)})'''
elif "file" in prompt.lower() or "read" in prompt.lower():
code = '''def read_file(file_path):
with open(file_path, "r") as f:
return f.read()
def write_file(file_path, content):
with open(file_path, "w") as f:
f.write(content)'''
else:
code = f'''# Generated code for: {prompt}
def generated_function():
print("Hello from generated code!")
return True
if __name__ == "__main__":
result = generated_function()
print(f"Result: {result}")'''
return {"code": code, "prompt": prompt}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
```