Spaces:
Build error
Build error
File size: 28,530 Bytes
ae7ae2c | 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 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 | <!DOCTYPE html>
<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> |