Spaces:
Build error
Build error
| <html lang="en"> | |
| <head> | |
| <meta charset="UTF-8"> | |
| <meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
| <title>ComfyUI Workflow</title> | |
| <style> | |
| body { | |
| font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Text', sans-serif; | |
| background-color: #000000; | |
| color: #f5f5f7; | |
| padding: 40px; | |
| } | |
| pre { | |
| background: #1d1d1f; | |
| padding: 24px; | |
| border-radius: 12px; | |
| overflow-x: auto; | |
| } | |
| </style> | |
| </head> | |
| <body> | |
| <h1>ComfyUI Workflow</h1> | |
| <p>Error: Invalid JSON format</p> | |
| <pre>```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 <Component {...pageProps} /> | |
| } | |
| === 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 ( | |
| <div className="flex h-screen overflow-hidden bg-slate-50"> | |
| <Sidebar | |
| activeFilter={activeFilter} | |
| setActiveFilter={setActiveFilter} | |
| /> | |
| <div className="flex-1 flex flex-col min-w-0"> | |
| <Header | |
| searchQuery={searchQuery} | |
| setSearchQuery={setSearchQuery} | |
| /> | |
| <main className="flex-1 flex overflow-hidden"> | |
| <CodeList | |
| codes={filteredCodes} | |
| selectedId={selectedId} | |
| setSelectedId={setSelectedId} | |
| /> | |
| <div className="flex-1 bg-white border-l border-slate-200 overflow-y-auto flex flex-col"> | |
| {selectedCode ? ( | |
| <CodeDisplay | |
| code={selectedCode} | |
| onDelete={() => deleteCode(selectedCode.id)} | |
| onCopy={() => copyCode(selectedCode.code)} | |
| onDownload={() => downloadCode(selectedCode.code, selectedCode.title)} | |
| /> | |
| ) : ( | |
| <div className="h-full flex flex-col items-center justify-center text-slate-400 p-8 text-center"> | |
| <div className="bg-slate-100 p-6 rounded-full mb-4"> | |
| <Code size={48} className="text-slate-300" /> | |
| </div> | |
| <h3 className="text-lg font-medium text-slate-600">No code selected</h3> | |
| <p className="max-w-xs">Select a code snippet from the list or generate new Python code using the prompt below.</p> | |
| </div> | |
| )} | |
| <div className="p-6 border-t border-slate-200 bg-slate-50"> | |
| <div className="max-w-3xl mx-auto"> | |
| <label className="block text-sm font-medium text-slate-700 mb-2">Generate New Python Code</label> | |
| <div className="flex gap-3"> | |
| <input | |
| type="text" | |
| placeholder="Describe what you want to generate (e.g., 'Create a function to calculate fibonacci sequence')" | |
| className="flex-1 px-4 py-3 bg-white border border-slate-300 focus:ring-2 focus:ring-python-blue focus:border-transparent rounded-lg outline-none text-slate-700" | |
| value={prompt} | |
| onChange={(e) => setPrompt(e.target.value)} | |
| disabled={isGenerating} | |
| /> | |
| <button | |
| onClick={generateCode} | |
| disabled={isGenerating || !prompt.trim()} | |
| className="px-6 py-3 bg-python-blue hover:bg-blue-700 disabled:bg-slate-400 text-white rounded-lg font-medium transition-colors flex items-center gap-2" | |
| > | |
| {isGenerating ? ( | |
| <span className="animate-pulse">Generating...</span> | |
| ) : ( | |
| <> | |
| <Sparkles size={18} /> | |
| Generate | |
| </> | |
| )} | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| </main> | |
| </div> | |
| {notification && ( | |
| <div className="fixed bottom-6 left-1/2 -translate-x-1/2 z-50 flex items-center gap-3 px-4 py-3 rounded-lg shadow-2xl animate-bounce bg-slate-900 text-white border border-slate-700"> | |
| {notification.type === 'success' ? <CheckCircle2 size={18} className="text-green-400" /> : <AlertCircle size={18} className="text-red-400" />} | |
| <span className="text-sm font-medium">{notification.message}</span> | |
| </div> | |
| )} | |
| </div> | |
| ); | |
| } | |
| === components/Header.js === | |
| import { Search, Menu, Settings, HelpCircle, Grid, Code } from 'lucide-react'; | |
| export default function Header({ searchQuery, setSearchQuery }) { | |
| return ( | |
| <header className="h-16 bg-white border-b border-slate-200 flex items-center justify-between px-4 shrink-0"> | |
| <div className="flex items-center gap-4"> | |
| <button className="p-2 hover:bg-slate-100 rounded-full text-slate-600"> | |
| <Menu size={20} /> | |
| </button> | |
| <div className="flex items-center gap-2"> | |
| <div className="bg-python-blue p-1.5 rounded-lg"> | |
| <Code size={16} className="text-white" /> | |
| </div> | |
| <span className="text-xl font-semibold text-slate-700 tracking-tight">Python<span className="font-normal text-slate-400">Generator</span></span> | |
| </div> | |
| </div> | |
| <div className="flex-1 max-w-2xl mx-8"> | |
| <div className="relative group"> | |
| <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none"> | |
| <Search size={18} className="text-slate-400 group-focus-within:text-python-blue transition-colors" /> | |
| </div> | |
| <input | |
| type="text" | |
| placeholder="Search code snippets..." | |
| className="w-full pl-10 pr-4 py-2 bg-slate-100 border-transparent focus:bg-white focus:ring-2 focus:ring-python-blue focus:border-transparent rounded-lg transition-all outline-none text-slate-700" | |
| value={searchQuery} | |
| onChange={(e) => setSearchQuery(e.target.value)} | |
| /> | |
| </div> | |
| </div> | |
| <div className="flex items-center gap-2"> | |
| <button className="p-2 hover:bg-slate-100 rounded-full text-slate-600 hidden md:block"> | |
| <HelpCircle size={20} /> | |
| </button> | |
| <button className="p-2 hover:bg-slate-100 rounded-full text-slate-600 hidden md:block"> | |
| <Settings size={20} /> | |
| </button> | |
| <button className="p-2 hover:bg-slate-100 rounded-full text-slate-600 hidden md:block"> | |
| <Grid size={20} /> | |
| </button> | |
| <div className="ml-2 w-8 h-8 bg-python-blue rounded-full flex items-center justify-center text-white text-xs font-bold border-2 border-white shadow-sm"> | |
| PY | |
| </div> | |
| </div> | |
| </header> | |
| ); | |
| } | |
| === 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 ( | |
| <aside className="w-64 bg-slate-50 border-r border-slate-200 flex flex-col shrink-0"> | |
| <div className="p-4"> | |
| <button className="flex items-center gap-3 px-6 py-4 bg-white shadow-md hover:shadow-lg transition-shadow rounded-2xl text-slate-700 font-medium border border-slate-100"> | |
| <Code size={20} className="text-python-blue" /> | |
| New Project | |
| </button> | |
| </div> | |
| <nav className="flex-1 px-3 space-y-1 overflow-y-auto"> | |
| <div className="mb-4"> | |
| <p className="px-3 text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Library</p> | |
| {menuItems.map((item) => ( | |
| <button | |
| key={item.id} | |
| onClick={() => setActiveFilter(item.id)} | |
| className={`w-full flex items-center justify-between px-3 py-2 rounded-r-full transition-colors text-sm ${ | |
| activeFilter === item.id | |
| ? 'bg-blue-100 text-blue-700 font-semibold' | |
| : 'text-slate-600 hover:bg-slate-200' | |
| }`} | |
| > | |
| <div className="flex items-center gap-3"> | |
| <item.icon size={18} /> | |
| <span>{item.label}</span> | |
| </div> | |
| {item.count > 0 && <span className="text-xs font-medium">{item.count}</span>} | |
| </button> | |
| ))} | |
| </div> | |
| <div> | |
| <p className="px-3 text-xs font-semibold text-slate-400 uppercase tracking-wider mb-2">Complexity</p> | |
| {labels.map((label) => ( | |
| <button | |
| key={label.id} | |
| onClick={() => setActiveFilter(label.id)} | |
| className={`w-full flex items-center gap-3 px-3 py-2 rounded-r-full transition-colors text-sm ${ | |
| activeFilter === label.id | |
| ? 'bg-blue-100 text-blue-700 font-semibold' | |
| : 'text-slate-600 hover:bg-slate-200' | |
| }`} | |
| > | |
| <label.icon size={18} className={label.color.replace('bg-', 'text-')} /> | |
| <span>{label.label}</span> | |
| </button> | |
| ))} | |
| </div> | |
| </nav> | |
| <div className="p-4 border-t border-slate-200"> | |
| <a | |
| href="https://huggingface.co/spaces/akhaliq/anycoder" | |
| target="_blank" | |
| rel="noopener noreferrer" | |
| className="block text-center text-xs text-slate-400 hover:text-python-blue transition-colors py-2" | |
| > | |
| Built with anycoder | |
| </a> | |
| </div> | |
| </aside> | |
| ); | |
| } | |
| === components/CodeList.js === | |
| import { Star, Archive, Trash2, Code } from 'lucide-react'; | |
| export default function CodeList({ codes, selectedId, setSelectedId }) { | |
| return ( | |
| <div className="w-full max-w-md bg-white border-r border-slate-200 flex flex-col shrink-0"> | |
| <div className="p-4 border-b border-slate-100 flex items-center justify-between"> | |
| <h2 className="font-semibold text-slate-700">Code Snippets</h2> | |
| <div className="flex gap-1"> | |
| <button className="p-1.5 hover:bg-slate-100 rounded text-slate-500"> | |
| <Code size={16} /> | |
| </button> | |
| </div> | |
| </div> | |
| <div className="flex-1 overflow-y-auto"> | |
| {codes.length === 0 ? ( | |
| <div className="p-8 text-center text-slate-400 text-sm"> | |
| No code snippets found matching your search. | |
| </div> | |
| ) : ( | |
| codes.map((code) => ( | |
| <div | |
| key={code.id} | |
| onClick={() => 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' | |
| }`} | |
| > | |
| <div className="flex justify-between items-start mb-1"> | |
| <span className="text-sm text-slate-900 font-medium"> | |
| {code.title} | |
| </span> | |
| <span className="text-xs text-slate-400">{code.date}</span> | |
| </div> | |
| <div className="text-xs text-slate-500 truncate mb-1"> | |
| {code.language} · {code.complexity} | |
| </div> | |
| <div className="text-xs text-slate-400 truncate font-mono bg-slate-100 p-2 rounded"> | |
| {code.code.substring(0, 50)}... | |
| </div> | |
| <div className="absolute right-2 top-1/2 -translate-y-1/2 opacity-0 group-hover:opacity-100 flex gap-1 transition-opacity"> | |
| <button className="p-1.5 hover:bg-slate-200 rounded-full text-slate-500"> | |
| <Archive size={14} /> | |
| </button> | |
| <button className="p-1.5 hover:bg-slate-200 rounded-full text-slate-500"> | |
| <Trash2 size={14} /> | |
| </button> | |
| </div> | |
| </div> | |
| )) | |
| )} | |
| </div> | |
| </div> | |
| ); | |
| } | |
| === components/CodeDisplay.js === | |
| import { Copy, Download, Trash2, Archive, MoreVertical, Star, Play, Code } from 'lucide-react'; | |
| export default function CodeDisplay({ code, onDelete, onCopy, onDownload }) { | |
| return ( | |
| <div className="h-full flex flex-col"> | |
| {/* Toolbar */} | |
| <div className="p-4 border-b border-slate-200 flex items-center justify-between shrink-0"> | |
| <div className="flex items-center gap-4"> | |
| <button className="p-2 hover:bg-slate-100 rounded-full text-slate-600"> | |
| <Archive size={18} /> | |
| </button> | |
| <button | |
| onClick={onDelete} | |
| className="p-2 hover:bg-red-50 rounded-full text-slate-600 hover:text-red-500 transition-colors" | |
| > | |
| <Trash2 size={18} /> | |
| </button> | |
| <div className="w-px h-6 bg-slate-200 mx-1" /> | |
| <button className="p-2 hover:bg-slate-100 rounded-full text-slate-600"> | |
| <Star size={18} /> | |
| </button> | |
| <button | |
| onClick={onCopy} | |
| className="p-2 hover:bg-slate-100 rounded-full text-slate-600" | |
| > | |
| <Copy size={18} /> | |
| </button> | |
| <button | |
| onClick={onDownload} | |
| className="p-2 hover:bg-slate-100 rounded-full text-slate-600" | |
| > | |
| <Download size={18} /> | |
| </button> | |
| </div> | |
| <div className="flex items-center gap-2"> | |
| <span className="px-3 py-1 bg-python-blue text-white text-xs rounded font-medium"> | |
| {code.language} | |
| </span> | |
| <span className={`px-3 py-1 text-xs rounded font-medium ${ | |
| code.complexity === 'complex' ? 'bg-red-100 text-red-600' : | |
| code.complexity === 'medium' ? 'bg-yellow-100 text-yellow-600' : 'bg-green-100 text-green-600' | |
| }`}> | |
| {code.complexity} | |
| </span> | |
| <button className="p-2 hover:bg-slate-100 rounded-full text-slate-600"> | |
| <MoreVertical size={18} /> | |
| </button> | |
| </div> | |
| </div> | |
| {/* Code Content */} | |
| <div className="flex-1 p-8 overflow-y-auto bg-slate-50"> | |
| <div className="max-w-4xl mx-auto"> | |
| <h1 className="text-2xl font-semibold text-slate-800 mb-4">{code.title}</h1> | |
| <div className="flex items-center justify-between mb-6"> | |
| <div className="flex items-center gap-3"> | |
| <div className="w-10 h-10 bg-python-blue rounded-full flex items-center justify-center text-white font-bold"> | |
| <Code size={20} /> | |
| </div> | |
| <div> | |
| <div className="font-medium text-slate-900">Generated Code</div> | |
| <div className="text-xs text-slate-500">Created {code.date}</div> | |
| </div> | |
| </div> | |
| </div> | |
| <div className="code-block text-slate-300 leading-relaxed whitespace-pre-wrap mb-8"> | |
| <pre className="font-mono text-sm"> | |
| <code>{code.code}</code> | |
| </pre> | |
| </div> | |
| {/* Action Buttons */} | |
| <div className="flex gap-3"> | |
| <button className="flex items-center gap-2 px-6 py-2 border border-slate-300 rounded-full text-slate-600 hover:bg-slate-50 transition-colors font-medium"> | |
| <Play size={16} /> | |
| Run Code | |
| </button> | |
| <button | |
| onClick={onCopy} | |
| className="flex items-center gap-2 px-6 py-2 border border-slate-300 rounded-full text-slate-600 hover:bg-slate-50 transition-colors font-medium" | |
| > | |
| <Copy size={16} /> | |
| Copy | |
| </button> | |
| <button | |
| onClick={onDownload} | |
| className="flex items-center gap-2 px-6 py-2 bg-python-blue text-white rounded-full hover:bg-blue-700 transition-colors font-medium" | |
| > | |
| <Download size={16} /> | |
| Download | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| ); | |
| } | |
| === 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) | |
| ```</pre> | |
| </body> | |
| </html> |