Spaces:
Sleeping
Sleeping
new UI
Browse filesFiles changed (23)
- .dockerignoreAdded+67
- DockerfileAdded+91
- README.md+99-107
- README_GRADIO.mdAdded+145
- backend_api.pyAdded+499
- frontend/.gitignoreAdded+35
- frontend/next.config.jsAdded+26
- frontend/package-lock.jsonAdded
- frontend/package.jsonAdded+35
- frontend/postcss.config.jsAdded+7
- frontend/src/app/globals.cssAdded+114
- frontend/src/app/layout.tsxAdded+23
- frontend/src/app/page.tsxAdded+278
- frontend/src/components/ChatInterface.tsxAdded+119
- frontend/src/components/CodeEditor.tsxAdded+60
- frontend/src/components/ControlPanel.tsxAdded+132
- frontend/src/components/Header.tsxAdded+179
- frontend/src/types/index.tsAdded+60
- frontend/tailwind.config.jsAdded+29
- frontend/tsconfig.jsonAdded+27
- start_backend.shAdded+21
- start_frontend.shAdded+18
- start_fullstack.shAdded+53
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667# Python__pycache__/*.py[cod]*$py.class*.so.Pythonvenv/.venv/ENV/env/*.egg-info/dist/build/
# Nodenode_modules/npm-debug.log*yarn-debug.log*yarn-error.log*.pnpm-debug.log*
# Next.jsfrontend/.next/frontend/out/frontend/build/
# Git.git/.gitignore
# IDE.vscode/.idea/*.swp*.swo*~
# OS.DS_StoreThumbs.db
# Documentation*.md!README.md
# DockerDockerfile*docker-compose*.yml.dockerignore
# Logs*.loglogs/log/
# Generatedgenerated_projects/
# Teststest/tests/__tests__/
# Lock files (will be regenerated)uv.lockpoetry.lock
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091# Multi-stage build for AnyCoder Docker Space
# Stage 1: Build frontendFROM node:18-slim AS frontend-builder
WORKDIR /build
# Copy frontend package filesCOPY frontend/package*.json ./RUN npm ci
# Copy frontend sourceCOPY frontend/ ./
# Build frontendRUN npm run build
# Stage 2: Production imageFROM python:3.11-slim
# Set up a new user named "user" with user ID 1000RUN useradd -m -u 1000 user
# Switch to the "user" userUSER user
# Set home to the user's home directoryENV HOME=/home/user \ PATH=/home/user/.local/bin:$PATH \ PYTHONUNBUFFERED=1
# Set the working directory to the user's home directoryWORKDIR $HOME/app
# Copy Python requirements and install dependenciesCOPY --chown=user:user requirements.txt .RUN pip install --no-cache-dir --upgrade pip && \ pip install --no-cache-dir -r requirements.txt
# Copy application codeCOPY --chown=user:user anycoder_app/ ./anycoder_app/COPY --chown=user:user backend_api.py .COPY --chown=user:user app.py .
# Copy built frontend from builder stageCOPY --chown=user:user --from=frontend-builder /build/.next ./frontend/.nextCOPY --chown=user:user --from=frontend-builder /build/public ./frontend/publicCOPY --chown=user:user --from=frontend-builder /build/package*.json ./frontend/COPY --chown=user:user --from=frontend-builder /build/next.config.js ./frontend/COPY --chown=user:user --from=frontend-builder /build/node_modules ./frontend/node_modules
# Install Node.js for running frontendUSER rootRUN apt-get update && \ apt-get install -y --no-install-recommends nodejs npm && \ rm -rf /var/lib/apt/lists/*USER user
# Set environment variables for the applicationENV BACKEND_HOST=http://localhost:8000 \ PORT=7860
# Create startup script that runs both services# Backend on 8000, Frontend on 7860 (exposed port)RUN echo '#!/bin/bash\n\set -e\n\\n\echo "οΏ½οΏ½ Starting AnyCoder Docker Space..."\n\\n\# Start backend on port 8000 in background\n\echo "οΏ½οΏ½ Starting FastAPI backend on port 8000..."\n\cd $HOME/app\n\uvicorn backend_api:app --host 0.0.0.0 --port 8000 &\n\BACKEND_PID=$!\n\\n\# Wait for backend to be ready\n\echo "β³ Waiting for backend to start..."\n\sleep 5\n\\n\# Start frontend on port 7860 (HF Spaces exposed port)\n\echo "οΏ½οΏ½ Starting Next.js frontend on port 7860..."\n\cd $HOME/app/frontend\n\PORT=7860 BACKEND_HOST=http://localhost:8000 npm start\n\' > $HOME/app/start.sh && chmod +x $HOME/app/start.sh
# Expose port 7860 (HF Spaces default)EXPOSE 7860
# Run the startup scriptCMD ["./start.sh"]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143---title: Anycoderemoji: π₯colorFrom: indigocolorTo: indigosdk: gradiosdk_version: 5.49.1app_file: app.pypinned: falsedisable_embedding: truehf_oauth: truehf_oauth_scopes:- manage-repos---# AnyCoder - AI Code GeneratorAnyCoder is an AI-powered code generator that helps you create applications by describing them in plain English. It supports multiple AI models, multimodal input, website redesign, and one-click deployment to Hugging Face Spaces. The UI is built with Gradio theming for a minimal, modern experience.## Features- **Multi-Model Support**: Choose from Moonshot Kimi-K2, Kimi K2 Turbo (Preview), Kimi K2 Thinking, DeepSeek V3, DeepSeek R1, ERNIE-4.5-VL, MiniMax M2, Qwen3-235B-A22B, Qwen3-30B-A3B-Instruct-2507, Qwen3-30B-A3B-Thinking-2507, SmolLM3-3B, GLM-4.1V-9B-Thinking, Gemini 2.5 Flash and Gemini 2.5 Pro (OpenAI-compatible)- Claude-Opus-4.1 (via Poe)- **Flexible Input**: Describe your app in text, upload a UI design image (for multimodal models), provide a reference file (PDF, TXT, MD, CSV, DOCX, or image), or enter a website URL for redesign- **Web Search Integration**: Enable real-time web search (Tavily, with advanced search depth) to enhance code generation with up-to-date information and best practices- **Code Generation**: Generate code in HTML, Python, JS, and more. Special support for transformers.js apps (outputs index.html, index.js, style.css)- **Live Preview**: Instantly preview generated HTML in a sandboxed iframe- **Modify Existing Code**: Use search/replace block format to update generated HTML- **One-Click Deployment**: Deploy your app to Hugging Face Spaces (Gradio, Streamlit, Static HTML, or Transformers.js) with OAuth login- **History & Examples**: Chat-like history of all interactions and quick example prompts for fast prototyping- **Minimal, Modern UI**: Built with Gradio 5.x, using only built-in theming and styling (no custom CSS)## Installation1. Clone the repository:```bashgit clone <repository-url>cd anycoder```2. Install dependencies:```bashpip install -r requirements.txt```3. Set up environment variables:```bashexport HF_TOKEN="your_huggingface_token"export DASHSCOPE_API_KEY="your_dashscope_api_key" # Required for Qwen3-30B models via DashScopeexport POE_API_KEY="your_poe_api_key" # Required for GPT-5, Grok-4, and Grok-Code-Fast-1 via Poeexport GEMINI_API_KEY="your_gemini_api_key" # Required for Gemini modelsexport MOONSHOT_API_KEY="your_moonshot_api_key" # Required for Kimi modelsexport MINIMAX_API_KEY="your_minimax_api_key" # Required for MiniMax M2 model```## Usage1. Run the application:```bashpython app.py```2. Open your browser and navigate to the provided URL3. Describe your application in the text input field, or:- Upload a UI design image (for multimodal models)- Upload a reference file (PDF, TXT, MD, CSV, DOCX, or image)- Enter a website URL for redesign (the app will extract and analyze the HTML and content)- Enable web search for up-to-date information- Choose a different AI model or code language4. Click "Generate" to create your code5. View the generated code in the Code tab or see it in action in the Preview tab6. Use the History tab to review previous generations7. **Deploy to Space**: Enter a title and click "π Deploy App" to publish your application (OAuth login required) - the SDK is automatically matched to your selected code language## Supported Models- Moonshot Kimi-K2- Kimi K2 Turbo (Preview)- Kimi K2 Thinking- DeepSeek V3- DeepSeek V3.1- DeepSeek V3.1 Terminus- DeepSeek V3.2-Exp- DeepSeek R1- MiniMax M2- Qwen3-235B-A22B- Qwen3-4B-Instruct-2507- Qwen3-4B-Thinking-2507- Qwen3-30B-A3B-Instruct-2507 (via DashScope)- Qwen3-30B-A3B-Thinking-2507 (via DashScope)- GPT-5 (via Poe)- Grok-4 (via Poe)- Claude-Opus-4.1 (via Poe)- Gemini 2.5 Flash (OpenAI-compatible)- Gemini 2.5 Pro (OpenAI-compatible)## Input Options- **Text Prompt**: Describe your app or code requirements- **Image Upload**: For multimodal models, upload a UI design image to generate code from visuals- **File Upload**: Provide a reference file (PDF, TXT, MD, CSV, DOCX, or image) for code generation or text extraction (OCR for images)- **Website URL**: Enter a URL to extract and redesign the website (HTML and content are analyzed and modernized)## Code Generation & Modification- Generates code in HTML, Python, JS, and more (selectable via dropdown)- Special support for transformers.js apps (outputs index.html, index.js, style.css)- Svelte apps- For HTML, provides a live preview in a sandboxed iframe- For modification requests, uses a search/replace block format to update existing HTML## Deployment- Deploy generated apps to Hugging Face Spaces directly from the UI- Supported SDKs: Gradio (Python), Streamlit (Python), Static (HTML), Transformers.js- OAuth login with Hugging Face is required for deployment to user-owned Spaces## History & Examples- Maintains a chat-like history of user/assistant interactions- Quick example prompts are available in the sidebar for fast prototyping## UI/UX- Built with Gradio 5.x, using only Gradio's built-in theming and styling (no custom CSS)- Minimal, uncluttered sidebar and interface## Environment Variables- `HF_TOKEN`: Your Hugging Face API token (required)- `GEMINI_API_KEY`: Your Google Gemini API key (required to use Gemini models)- `MOONSHOT_API_KEY`: Your Moonshot AI API key (required to use Kimi models)- `MINIMAX_API_KEY`: Your MiniMax API key (required to use MiniMax M2 model)## Project Structure```anycoder/βββ app.py # Main application (all logic and UI)βββ requirements.txtβββ README.md # This file```## License[Add your license information here]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135---title: AnyCoderemoji: πcolorFrom: bluecolorTo: purplesdk: dockerapp_port: 7860pinned: falsedisable_embedding: falsehf_oauth: truehf_oauth_scopes:- manage-repos---> **Note:** This is the Docker Space configuration for the React frontend version.> For the original Gradio app, see `README_GRADIO.md`.# AnyCoder - AI Code Generator with React FrontendAnyCoder is a full-stack AI-powered code generator with a modern React/TypeScript frontend and FastAPI backend. Generate applications by describing them in plain English, with support for multiple AI models and one-click deployment to Hugging Face Spaces.## π¨ Features- **Modern React UI**: Apple-inspired design with VS Code layout- **Real-time Streaming**: Server-Sent Events for live code generation- **Multi-Model Support**: MiniMax M2, DeepSeek V3, and more via HuggingFace InferenceClient- **Multiple Languages**: HTML, Gradio, Streamlit, React, Transformers.js, ComfyUI- **Authentication**: HuggingFace OAuth + Dev mode for local testing- **One-Click Deployment**: Deploy generated apps directly to HF Spaces## ποΈ Architecture```anycoder/βββ backend_api.py # FastAPI backend with streamingβββ frontend/ # Next.js React frontendβ βββ src/β β βββ app/ # Pages (page.tsx, layout.tsx, globals.css)β β βββ components/ # React componentsβ β βββ lib/ # API client, auth utilitiesβ β βββ types/ # TypeScript typesβ βββ package.jsonβββ anycoder_app/ # Original Gradio app modulesβ βββ agent.pyβ βββ config.pyβ βββ deploy.pyβ βββ ...βββ app.py # Original Gradio interfaceβββ requirements.txt # Python dependenciesβββ Dockerfile # Docker Space configurationβββ start_fullstack.sh # Local development script```## π Quick Start### Local Development1. **Backend**:```bashexport HF_TOKEN="your_huggingface_token"python backend_api.py```2. **Frontend** (new terminal):```bashcd frontendnpm installnpm run dev```3. Open `http://localhost:3000`### Using start script:```bashexport HF_TOKEN="your_token"./start_fullstack.sh```## π³ Docker Space DeploymentThis app runs as a Docker Space on HuggingFace. The Dockerfile:- Builds the Next.js frontend- Runs FastAPI backend on port 7860- Uses proper user permissions (UID 1000)- Handles environment variables securely## π Authentication- **Dev Mode** (localhost): Mock login for testing- **Production**: HuggingFace OAuth with manage-repos scope## π Supported Languages- `html` - Static HTML pages- `gradio` - Python Gradio apps- `streamlit` - Python Streamlit apps- `react` - React/Next.js apps- `transformers.js` - Browser ML apps- `comfyui` - ComfyUI workflows## π€ Available Models- MiniMax M2 (via HF router with Novita)- DeepSeek V3/V3.1- DeepSeek R1- And more via HuggingFace InferenceClient## π― Usage1. Sign in with HuggingFace (or use Dev Login locally)2. Select a language and AI model3. Describe your app in the chat4. Watch code generate in real-time5. Click **π Deploy** to publish to HF Spaces## π οΈ Environment Variables- `HF_TOKEN` - HuggingFace API token (required)## π¦ Tech Stack**Frontend:**- Next.js 14- TypeScript- Tailwind CSS- Monaco Editor**Backend:**- FastAPI- HuggingFace Hub- Server-Sent Events (SSE)## π LicenseMIT
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145---title: Anycoderemoji: π₯colorFrom: indigocolorTo: indigosdk: gradiosdk_version: 5.49.1app_file: app.pypinned: falsedisable_embedding: truehf_oauth: truehf_oauth_scopes:- manage-repos---
# AnyCoder - AI Code Generator
> **π± New:** A React/TypeScript frontend version is now the default! This file is the backup Gradio version. For the Docker Space with modern React UI, see `README.md`.
AnyCoder is an AI-powered code generator that helps you create applications by describing them in plain English. It supports multiple AI models, multimodal input, website redesign, and one-click deployment to Hugging Face Spaces. The UI is built with Gradio theming for a minimal, modern experience.
## Features
- **Multi-Model Support**: Choose from Moonshot Kimi-K2, Kimi K2 Turbo (Preview), Kimi K2 Thinking, DeepSeek V3, DeepSeek R1, ERNIE-4.5-VL, MiniMax M2, Qwen3-235B-A22B, Qwen3-30B-A3B-Instruct-2507, Qwen3-30B-A3B-Thinking-2507, SmolLM3-3B, GLM-4.1V-9B-Thinking, Gemini 2.5 Flash and Gemini 2.5 Pro (OpenAI-compatible) - Claude-Opus-4.1 (via Poe)- **Flexible Input**: Describe your app in text, upload a UI design image (for multimodal models), provide a reference file (PDF, TXT, MD, CSV, DOCX, or image), or enter a website URL for redesign- **Web Search Integration**: Enable real-time web search (Tavily, with advanced search depth) to enhance code generation with up-to-date information and best practices- **Code Generation**: Generate code in HTML, Python, JS, and more. Special support for transformers.js apps (outputs index.html, index.js, style.css)- **Live Preview**: Instantly preview generated HTML in a sandboxed iframe- **Modify Existing Code**: Use search/replace block format to update generated HTML- **One-Click Deployment**: Deploy your app to Hugging Face Spaces (Gradio, Streamlit, Static HTML, or Transformers.js) with OAuth login- **History & Examples**: Chat-like history of all interactions and quick example prompts for fast prototyping- **Minimal, Modern UI**: Built with Gradio 5.x, using only built-in theming and styling (no custom CSS)
## Installation
1. Clone the repository:```bashgit clone <repository-url>cd anycoder```2. Install dependencies:```bashpip install -r requirements.txt```3. Set up environment variables:```bashexport HF_TOKEN="your_huggingface_token"export DASHSCOPE_API_KEY="your_dashscope_api_key" # Required for Qwen3-30B models via DashScopeexport POE_API_KEY="your_poe_api_key" # Required for GPT-5, Grok-4, and Grok-Code-Fast-1 via Poeexport GEMINI_API_KEY="your_gemini_api_key" # Required for Gemini modelsexport MOONSHOT_API_KEY="your_moonshot_api_key" # Required for Kimi modelsexport MINIMAX_API_KEY="your_minimax_api_key" # Required for MiniMax M2 model```
## Usage
1. Run the application:```bashpython app.py```2. Open your browser and navigate to the provided URL3. Describe your application in the text input field, or: - Upload a UI design image (for multimodal models) - Upload a reference file (PDF, TXT, MD, CSV, DOCX, or image) - Enter a website URL for redesign (the app will extract and analyze the HTML and content) - Enable web search for up-to-date information - Choose a different AI model or code language4. Click "Generate" to create your code5. View the generated code in the Code tab or see it in action in the Preview tab6. Use the History tab to review previous generations7. **Deploy to Space**: Enter a title and click "π Deploy App" to publish your application (OAuth login required) - the SDK is automatically matched to your selected code language
## Supported Models
- Moonshot Kimi-K2- Kimi K2 Turbo (Preview)- Kimi K2 Thinking- DeepSeek V3- DeepSeek V3.1- DeepSeek V3.1 Terminus- DeepSeek V3.2-Exp- DeepSeek R1- MiniMax M2- Qwen3-235B-A22B- Qwen3-4B-Instruct-2507- Qwen3-4B-Thinking-2507- Qwen3-30B-A3B-Instruct-2507 (via DashScope)- Qwen3-30B-A3B-Thinking-2507 (via DashScope)- GPT-5 (via Poe)- Grok-4 (via Poe) - Claude-Opus-4.1 (via Poe) - Gemini 2.5 Flash (OpenAI-compatible) - Gemini 2.5 Pro (OpenAI-compatible)
## Input Options
- **Text Prompt**: Describe your app or code requirements- **Image Upload**: For multimodal models, upload a UI design image to generate code from visuals- **File Upload**: Provide a reference file (PDF, TXT, MD, CSV, DOCX, or image) for code generation or text extraction (OCR for images)- **Website URL**: Enter a URL to extract and redesign the website (HTML and content are analyzed and modernized)
## Code Generation & Modification
- Generates code in HTML, Python, JS, and more (selectable via dropdown)- Special support for transformers.js apps (outputs index.html, index.js, style.css)- Svelte apps- For HTML, provides a live preview in a sandboxed iframe- For modification requests, uses a search/replace block format to update existing HTML
## Deployment
- Deploy generated apps to Hugging Face Spaces directly from the UI- Supported SDKs: Gradio (Python), Streamlit (Python), Static (HTML), Transformers.js- OAuth login with Hugging Face is required for deployment to user-owned Spaces
## History & Examples
- Maintains a chat-like history of user/assistant interactions- Quick example prompts are available in the sidebar for fast prototyping
## UI/UX
- Built with Gradio 5.x, using only Gradio's built-in theming and styling (no custom CSS)- Minimal, uncluttered sidebar and interface
## Environment Variables
- `HF_TOKEN`: Your Hugging Face API token (required) - `GEMINI_API_KEY`: Your Google Gemini API key (required to use Gemini models)- `MOONSHOT_API_KEY`: Your Moonshot AI API key (required to use Kimi models)- `MINIMAX_API_KEY`: Your MiniMax API key (required to use MiniMax M2 model)
## Project Structure
```anycoder/βββ app.py # Main application (all logic and UI)βββ requirements.txtβββ README.md # This file```
## License
[Add your license information here]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499"""FastAPI backend for AnyCoder - provides REST API endpoints"""from fastapi import FastAPI, HTTPException, Header, WebSocket, WebSocketDisconnectfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import StreamingResponsefrom pydantic import BaseModelfrom typing import Optional, List, Dict, AsyncGeneratorimport jsonimport asynciofrom datetime import datetime
# Import only what we need, avoiding Gradio UI importsimport sysimport osfrom huggingface_hub import InferenceClient
# Define models and languages here to avoid importing Gradio UIAVAILABLE_MODELS = [ {"name": "Sherlock Dash Alpha", "id": "openrouter/sherlock-dash-alpha", "description": "Sherlock Dash Alpha model via OpenRouter"}, {"name": "MiniMax M2", "id": "MiniMaxAI/MiniMax-M2", "description": "MiniMax M2 model via HuggingFace InferenceClient with Novita provider"}, {"name": "DeepSeek V3.2-Exp", "id": "deepseek-ai/DeepSeek-V3.2-Exp", "description": "DeepSeek V3.2 Experimental via HuggingFace"}, {"name": "DeepSeek R1", "id": "deepseek-ai/DeepSeek-R1-0528", "description": "DeepSeek R1 model for code generation"}, {"name": "GPT-5", "id": "gpt-5", "description": "OpenAI GPT-5 via OpenRouter"}, {"name": "Gemini Flash Latest", "id": "gemini-flash-latest", "description": "Google Gemini Flash via OpenRouter"}, {"name": "Qwen3 Max Preview", "id": "qwen3-max-preview", "description": "Qwen3 Max Preview via DashScope API"},]
LANGUAGE_CHOICES = ["html", "gradio", "transformers.js", "streamlit", "comfyui", "react"]
app = FastAPI(title="AnyCoder API", version="1.0.0")
# Configure CORSapp.add_middleware( CORSMiddleware, allow_origins=["http://localhost:3000", "http://localhost:3001"], # Frontend URLs allow_credentials=True, allow_methods=["*"], allow_headers=["*"],)
# Pydantic models for request/responseclass CodeGenerationRequest(BaseModel): query: str language: str = "html" model_id: str = "openrouter/sherlock-dash-alpha" provider: str = "auto" history: List[List[str]] = [] agent_mode: bool = False
class DeploymentRequest(BaseModel): code: str space_name: str language: str requirements: Optional[str] = None
class AuthStatus(BaseModel): authenticated: bool username: Optional[str] = None message: str
class ModelInfo(BaseModel): name: str id: str description: str
class CodeGenerationResponse(BaseModel): code: str history: List[List[str]] status: str
# Mock authentication for development# In production, integrate with HuggingFace OAuthclass MockAuth: def __init__(self, token: Optional[str] = None): self.token = token # Extract username from dev token or use generic name if token and token.startswith("dev_token_"): # Extract username from dev token format: dev_token_<username>_<timestamp> parts = token.split("_") self.username = parts[2] if len(parts) > 2 else "user" else: self.username = "user" if token else None def is_authenticated(self): # Accept any token (for dev mode) return bool(self.token)
def get_auth_from_header(authorization: Optional[str] = None): """Extract authentication from header""" if not authorization: return MockAuth(None) # Handle "Bearer " prefix if authorization.startswith("Bearer "): token = authorization.replace("Bearer ", "") else: token = authorization return MockAuth(token)
@app.get("/")async def root(): """Health check endpoint""" return {"status": "ok", "message": "AnyCoder API is running"}
@app.get("/api/models", response_model=List[ModelInfo])async def get_models(): """Get available AI models""" return [ ModelInfo( name=model["name"], id=model["id"], description=model["description"] ) for model in AVAILABLE_MODELS ]
@app.get("/api/languages")async def get_languages(): """Get available programming languages/frameworks""" return {"languages": LANGUAGE_CHOICES}
@app.get("/api/auth/status")async def auth_status(authorization: Optional[str] = Header(None)): """Check authentication status""" auth = get_auth_from_header(authorization) if auth.is_authenticated(): return AuthStatus( authenticated=True, username=auth.username, message=f"Authenticated as {auth.username}" ) return AuthStatus( authenticated=False, username=None, message="Not authenticated" )
@app.get("/api/generate")async def generate_code( query: str, language: str = "html", model_id: str = "openrouter/sherlock-dash-alpha", provider: str = "auto", authorization: Optional[str] = Header(None)): """Generate code based on user query - returns streaming response""" # Dev mode: No authentication required - just use server's HF_TOKEN # In production, you would check real OAuth tokens here async def event_stream() -> AsyncGenerator[str, None]: """Stream generated code chunks""" try: # Find the selected model selected_model = None for model in AVAILABLE_MODELS: if model["id"] == model_id: selected_model = model break if not selected_model: selected_model = AVAILABLE_MODELS[0] # Track generated code generated_code = "" # Use a simple system prompt system_prompt = "You are a helpful AI assistant that generates code based on user requirements. Generate clean, well-commented code." # Get the real model ID actual_model_id = selected_model["id"] # Determine which provider/API to use based on model ID if actual_model_id.startswith("openrouter/"): # OpenRouter models - use via OpenAI-compatible API api_key = os.getenv("OPENROUTER_API_KEY") or os.getenv("HF_TOKEN") client = InferenceClient(api_key=api_key, provider="openai", base_url="https://openrouter.ai/api/v1") # Keep the model_id as-is for OpenRouter elif actual_model_id == "MiniMaxAI/MiniMax-M2": # MiniMax M2 via HuggingFace with Novita provider hf_token = os.getenv("HF_TOKEN") if not hf_token: error_data = json.dumps({ "type": "error", "message": "HF_TOKEN environment variable not set. Please set it in your terminal.", "timestamp": datetime.now().isoformat() }) yield f"data: {error_data}\n\n" return # Use OpenAI client with HuggingFace router from openai import OpenAI client = OpenAI( base_url="https://router.huggingface.co/v1", api_key=hf_token, default_headers={ "X-HF-Bill-To": "huggingface" } ) # Add :novita suffix for the API call actual_model_id = "MiniMaxAI/MiniMax-M2:novita" elif actual_model_id.startswith("deepseek-ai/"): # DeepSeek models via HuggingFace client = InferenceClient(token=os.getenv("HF_TOKEN")) elif actual_model_id == "qwen3-max-preview": # Qwen via DashScope (would need separate implementation) # For now, fall back to HF client = InferenceClient(token=os.getenv("HF_TOKEN")) else: # Default: HuggingFace models client = InferenceClient(token=os.getenv("HF_TOKEN")) # Prepare messages messages = [ {"role": "system", "content": system_prompt}, {"role": "user", "content": f"Generate a {language} application: {query}"} ] # Stream the response try: stream = client.chat.completions.create( model=actual_model_id, messages=messages, temperature=0.7, max_tokens=10000, stream=True ) for chunk in stream: # Check if choices array has elements before accessing if (hasattr(chunk, 'choices') and chunk.choices and len(chunk.choices) > 0 and hasattr(chunk.choices[0], 'delta') and hasattr(chunk.choices[0].delta, 'content') and chunk.choices[0].delta.content): content = chunk.choices[0].delta.content generated_code += content # Send chunk as Server-Sent Event event_data = json.dumps({ "type": "chunk", "content": content, "timestamp": datetime.now().isoformat() }) yield f"data: {event_data}\n\n" await asyncio.sleep(0) # Allow other tasks to run # Send completion event completion_data = json.dumps({ "type": "complete", "code": generated_code, "timestamp": datetime.now().isoformat() }) yield f"data: {completion_data}\n\n" except Exception as e: error_data = json.dumps({ "type": "error", "message": str(e), "timestamp": datetime.now().isoformat() }) yield f"data: {error_data}\n\n" except Exception as e: error_data = json.dumps({ "type": "error", "message": f"Generation error: {str(e)}", "timestamp": datetime.now().isoformat() }) yield f"data: {error_data}\n\n" return StreamingResponse( event_stream(), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } )
@app.post("/api/deploy")async def deploy( request: DeploymentRequest, authorization: Optional[str] = Header(None)): """Deploy generated code to HuggingFace Spaces""" auth = get_auth_from_header(authorization) if not auth.is_authenticated(): raise HTTPException(status_code=401, detail="Authentication required") # Check if this is dev mode (no real token) if auth.token and auth.token.startswith("dev_token_"): # In dev mode, open HF Spaces creation page import urllib.parse base_url = "https://huggingface.co/new-space" # Map language to SDK language_to_sdk = { "gradio": "gradio", "streamlit": "docker", "react": "docker", "html": "static", "transformers.js": "static", "comfyui": "static" } sdk = language_to_sdk.get(request.language, "gradio") params = urllib.parse.urlencode({ "name": request.space_name or "my-anycoder-app", "sdk": sdk }) # Prepare file content based on language if request.language in ["html", "transformers.js", "comfyui"]: file_path = "index.html" else: file_path = "app.py" files_params = urllib.parse.urlencode({ "files[0][path]": file_path, "files[0][content]": request.code }) space_url = f"{base_url}?{params}&{files_params}" return { "success": True, "space_url": space_url, "message": "Dev mode: Please create the space manually", "dev_mode": True } # Production mode with real token try: from huggingface_hub import HfApi import tempfile import uuid # Get user token from header or use server token user_token = auth.token if auth.token else os.getenv("HF_TOKEN") if not user_token: raise HTTPException(status_code=401, detail="No HuggingFace token available") # Create API client api = HfApi(token=user_token) # Generate space name if not provided space_name = request.space_name or f"anycoder-{uuid.uuid4().hex[:8]}" repo_id = f"{auth.username}/{space_name}" # Map language to SDK language_to_sdk = { "gradio": "gradio", "streamlit": "docker", "react": "docker", "html": "static", "transformers.js": "static", "comfyui": "static" } sdk = language_to_sdk.get(request.language, "gradio") # Create the space try: api.create_repo( repo_id=repo_id, repo_type="space", space_sdk=sdk, exist_ok=False ) except Exception as e: if "already exists" in str(e).lower(): # Space exists, we'll update it pass else: raise # Upload the code file if request.language in ["html", "transformers.js", "comfyui"]: file_name = "index.html" else: file_name = "app.py" with tempfile.NamedTemporaryFile("w", suffix=f".{file_name.split('.')[-1]}", delete=False) as f: f.write(request.code) temp_path = f.name try: api.upload_file( path_or_fileobj=temp_path, path_in_repo=file_name, repo_id=repo_id, repo_type="space" ) # For Gradio apps, also upload requirements.txt if needed if request.language == "gradio": # Simple requirements for basic Gradio app requirements = "gradio>=4.0.0\n" with tempfile.NamedTemporaryFile("w", suffix=".txt", delete=False) as req_f: req_f.write(requirements) req_temp_path = req_f.name try: api.upload_file( path_or_fileobj=req_temp_path, path_in_repo="requirements.txt", repo_id=repo_id, repo_type="space" ) finally: os.unlink(req_temp_path) space_url = f"https://huggingface.co/spaces/{repo_id}" return { "success": True, "space_url": space_url, "message": f"β
Deployed successfully to {repo_id}!" } finally: os.unlink(temp_path) except Exception as e: raise HTTPException(status_code=500, detail=f"Deployment failed: {str(e)}")
@app.websocket("/ws/generate")async def websocket_generate(websocket: WebSocket): """WebSocket endpoint for real-time code generation""" await websocket.accept() try: while True: # Receive message from client data = await websocket.receive_json() query = data.get("query") language = data.get("language", "html") model_id = data.get("model_id", "openrouter/sherlock-dash-alpha") # Send acknowledgment await websocket.send_json({ "type": "status", "message": "Generating code..." }) # Mock code generation for now await asyncio.sleep(0.5) # Send generated code in chunks sample_code = f"<!-- Generated {language} code -->\n<h1>Hello from AnyCoder!</h1>" for i, char in enumerate(sample_code): await websocket.send_json({ "type": "chunk", "content": char, "progress": (i + 1) / len(sample_code) * 100 }) await asyncio.sleep(0.01) # Send completion await websocket.send_json({ "type": "complete", "code": sample_code }) except WebSocketDisconnect: print("Client disconnected") except Exception as e: await websocket.send_json({ "type": "error", "message": str(e) }) await websocket.close()
if __name__ == "__main__": import uvicorn uvicorn.run("backend_api:app", host="0.0.0.0", port=8000, reload=True)
1234567891011121314151617181920212223242526272829303132333435# dependencies/node_modules/.pnp.pnp.js
# testing/coverage
# next.js/.next//out/
# production/build
# misc.DS_Store*.pem
# debugnpm-debug.log*yarn-debug.log*yarn-error.log*
# local env files.env*.local.env
# vercel.vercel
# typescript*.tsbuildinfonext-env.d.ts
1234567891011121314151617181920212223242526/** @type {import('next').NextConfig} */const nextConfig = { output: 'standalone', reactStrictMode: true, env: { NEXT_PUBLIC_API_URL: process.env.NEXT_PUBLIC_API_URL || 'http://localhost:8000', }, async rewrites() { // In Docker Space, proxy /api/* requests to backend on port 8000 // This allows frontend (7860) to communicate with backend (8000) internally const API_HOST = process.env.BACKEND_HOST || 'http://localhost:8000'; return [ { source: '/api/:path*', destination: `${API_HOST}/api/:path*`, }, { source: '/ws/:path*', destination: `${API_HOST}/ws/:path*`, }, ]; },}
module.exports = nextConfig
1234567891011121314151617181920212223242526272829303132333435{ "name": "anycoder-frontend", "version": "1.0.0", "private": true, "scripts": { "dev": "next dev", "build": "next build", "start": "next start -p 7860", "lint": "next lint" }, "dependencies": { "next": "14.2.5", "react": "^18.3.1", "react-dom": "^18.3.1", "axios": "^1.7.2", "@monaco-editor/react": "^4.6.0", "@huggingface/hub": "^0.15.1", "prismjs": "^1.29.0", "react-markdown": "^9.0.1", "remark-gfm": "^4.0.0" }, "devDependencies": { "@types/node": "^20", "@types/react": "^18", "@types/react-dom": "^18", "@types/prismjs": "^1.26.4", "typescript": "^5", "eslint": "^8", "eslint-config-next": "14.2.5", "autoprefixer": "^10.4.19", "postcss": "^8.4.39", "tailwindcss": "^3.4.4" }}
1234567module.exports = { plugins: { tailwindcss: {}, autoprefixer: {}, },}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114@tailwind base;@tailwind components;@tailwind utilities;
* { box-sizing: border-box; padding: 0; margin: 0;}
html,body { height: 100%; overflow: hidden;}
body { color: #e5e5e7; background: #1d1d1f; font-family: -apple-system, BlinkMacSystemFont, 'SF Pro Display', 'SF Pro Text', 'Helvetica Neue', sans-serif; -webkit-font-smoothing: antialiased; -moz-osx-font-smoothing: grayscale; letter-spacing: -0.01em;}
/* Apple-style scrollbar */::-webkit-scrollbar { width: 12px; height: 12px;}
::-webkit-scrollbar-track { background: transparent;}
::-webkit-scrollbar-thumb { background: rgba(255, 255, 255, 0.2); border-radius: 10px; border: 3px solid #1d1d1f;}
::-webkit-scrollbar-thumb:hover { background: rgba(255, 255, 255, 0.3);}
::-webkit-scrollbar-corner { background: #1d1d1f;}
/* Markdown styling in chat - VS Code style */.prose { max-width: none; color: #cccccc;}
.prose code { background-color: #2d2d30; color: #d4d4d4; padding: 0.2em 0.4em; border-radius: 3px; font-size: 0.875em; font-family: 'SF Mono', 'Monaco', 'Menlo', 'Courier New', monospace;}
.prose pre { background-color: #1e1e1e; padding: 1em; border-radius: 4px; overflow-x: auto; border: 1px solid #3e3e42;}
.prose pre code { background-color: transparent; padding: 0;}
.prose p { margin: 0.5em 0;}
.prose a { color: #3794ff; text-decoration: none;}
.prose a:hover { text-decoration: underline;}
/* Selection color - Apple style */::selection { background-color: rgba(0, 122, 255, 0.3); color: #ffffff;}
::-moz-selection { background-color: rgba(0, 122, 255, 0.3); color: #ffffff;}
/* Apple-style focus rings */button:focus-visible,input:focus-visible,select:focus-visible { outline: 2px solid rgba(0, 122, 255, 0.6); outline-offset: 2px;}
/* Smooth transitions */* { transition: background-color 0.2s ease, border-color 0.2s ease, transform 0.2s ease;}
1234567891011121314151617181920212223import type { Metadata } from 'next';import { Inter } from 'next/font/google';import './globals.css';
const inter = Inter({ subsets: ['latin'] });
export const metadata: Metadata = { title: 'AnyCoder - AI Code Generator', description: 'Generate code with AI - supports HTML, Gradio, React, Streamlit, and more',};
export default function RootLayout({ children,}: { children: React.ReactNode;}) { return ( <html lang="en"> <body className={inter.className}>{children}</body> </html> );}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278'use client';
import { useState, useEffect } from 'react';import Header from '@/components/Header';import ChatInterface from '@/components/ChatInterface';import CodeEditor from '@/components/CodeEditor';import ControlPanel from '@/components/ControlPanel';import { apiClient } from '@/lib/api';import { isAuthenticated as checkIsAuthenticated, getStoredToken } from '@/lib/auth';import type { Message, Language, CodeGenerationRequest } from '@/types';
export default function Home() { const [messages, setMessages] = useState<Message[]>([]); const [generatedCode, setGeneratedCode] = useState(''); const [selectedLanguage, setSelectedLanguage] = useState<Language>('html'); const [selectedModel, setSelectedModel] = useState('openrouter/sherlock-dash-alpha'); const [isGenerating, setIsGenerating] = useState(false); const [isAuthenticated, setIsAuthenticated] = useState(false);
useEffect(() => { checkAuth(); // Check auth status every second to catch OAuth redirects const interval = setInterval(checkAuth, 1000); return () => clearInterval(interval); }, []);
const checkAuth = () => { const authenticated = checkIsAuthenticated(); setIsAuthenticated(authenticated); // Make sure API client has the token if (authenticated) { const token = getStoredToken(); if (token) { apiClient.setToken(token); } } };
const handleSendMessage = async (message: string) => { if (!isAuthenticated) { alert('Please sign in with HuggingFace first! Click the "Sign in with Hugging Face" button in the header.'); return; }
// Add user message const userMessage: Message = { role: 'user', content: message, timestamp: new Date().toISOString(), }; setMessages((prev) => [...prev, userMessage]); setIsGenerating(true);
// Prepare request const request: CodeGenerationRequest = { query: message, language: selectedLanguage, model_id: selectedModel, provider: 'auto', history: messages.map((m) => [m.role, m.content]), agent_mode: false, };
let generatedCodeBuffer = ''; const assistantMessage: Message = { role: 'assistant', content: 'β³ Generating code...', timestamp: new Date().toISOString(), };
// Add placeholder for assistant message setMessages((prev) => [...prev, assistantMessage]);
// Stream the response try { apiClient.generateCodeStream( request, // onChunk - Update code editor in real-time, NOT the chat (chunk: string) => { generatedCodeBuffer += chunk; setGeneratedCode(generatedCodeBuffer); }, // onComplete (code: string) => { setGeneratedCode(code); setIsGenerating(false); // Update final message - just show success, not the code setMessages((prev) => { const newMessages = [...prev]; newMessages[newMessages.length - 1] = { ...assistantMessage, content: 'β
Code generated successfully! Check the editor β', }; return newMessages; }); }, // onError (error: string) => { setIsGenerating(false); setMessages((prev) => { const newMessages = [...prev]; newMessages[newMessages.length - 1] = { ...assistantMessage, content: `β Error: ${error}`, }; return newMessages; }); } ); } catch (error) { setIsGenerating(false); setMessages((prev) => { const newMessages = [...prev]; newMessages[newMessages.length - 1] = { ...assistantMessage, content: `β Error: ${error instanceof Error ? error.message : 'Unknown error'}`, }; return newMessages; }); } };
const handleDeploy = async () => { if (!generatedCode) { alert('No code to deploy! Generate some code first.'); return; }
const spaceName = prompt('Enter HuggingFace Space name (or leave empty for auto-generated):'); if (spaceName === null) return; // User cancelled
try { const response = await apiClient.deploy({ code: generatedCode, space_name: spaceName || undefined, language: selectedLanguage, });
if (response.success) { // Open the space URL in a new tab window.open(response.space_url, '_blank'); // Show success message const isDev = response.dev_mode; const message = isDev ? 'π Opening HuggingFace Spaces creation page...\nPlease complete the space setup in the new tab.' : `β
Deployed successfully!\n\nOpening: ${response.space_url}`; alert(message); } else { alert(`Deployment failed: ${response.message}`); } } catch (error) { alert(`Deployment error: ${error instanceof Error ? error.message : 'Unknown error'}`); } };
const handleClear = () => { if (confirm('Clear all messages and code?')) { setMessages([]); setGeneratedCode(''); } };
return ( <div className="h-screen flex flex-col bg-[#1d1d1f]"> <Header /> {/* VS Code layout with Apple styling */} <main className="flex-1 flex overflow-hidden"> {/* Left Sidebar - Chat Panel */} <div className="w-80 bg-[#28282a] border-r border-[#48484a] flex flex-col shadow-xl"> {/* Panel Header */} <div className="flex items-center px-5 py-4 bg-[#28282a] border-b border-[#48484a]"> <div className="flex space-x-2"> <div className="w-3 h-3 rounded-full bg-[#ff5f57] shadow-sm"></div> <div className="w-3 h-3 rounded-full bg-[#ffbd2e] shadow-sm"></div> <div className="w-3 h-3 rounded-full bg-[#28ca41] shadow-sm"></div> </div> <span className="ml-4 text-sm font-semibold text-[#e5e5e7] tracking-tight">Chat</span> </div> {/* Chat Panel */} <div className="flex-1 overflow-hidden"> <ChatInterface messages={messages} onSendMessage={handleSendMessage} isGenerating={isGenerating} isAuthenticated={isAuthenticated} /> </div> </div>
{/* Center - Editor Group */} <div className="flex-1 flex flex-col bg-[#1d1d1f]"> {/* Tab Bar */} <div className="flex items-center px-5 h-11 bg-[#28282a] border-b border-[#48484a]"> <div className="flex items-center space-x-2"> <div className="px-4 py-1.5 bg-[#1d1d1f] border-t-2 border-[#007aff] text-sm text-[#e5e5e7] rounded-t-lg shadow-sm font-medium"> {selectedLanguage}.{selectedLanguage === 'html' ? 'html' : selectedLanguage === 'python' ? 'py' : 'js'} </div> </div> <div className="ml-auto flex items-center space-x-3 text-xs text-[#a1a1a6]"> {isGenerating && ( <span className="flex items-center space-x-1.5 animate-pulse"> <div className="w-2 h-2 bg-[#007aff] rounded-full shadow-lg"></div> <span className="font-medium">Generating...</span> </span> )} <span className="font-semibold tracking-wide">{selectedLanguage.toUpperCase()}</span> </div> </div> {/* Editor */} <div className="flex-1"> <CodeEditor code={generatedCode || '// Your generated code will appear here...\n// Select a model and start chatting to generate code'} language={selectedLanguage} onChange={setGeneratedCode} readOnly={isGenerating} /> </div> </div>
{/* Right Sidebar - Configuration Panel */} <div className="w-72 bg-[#28282a] border-l border-[#48484a] overflow-y-auto shadow-xl"> <ControlPanel selectedLanguage={selectedLanguage} selectedModel={selectedModel} onLanguageChange={setSelectedLanguage} onModelChange={setSelectedModel} onDeploy={handleDeploy} onClear={handleClear} isGenerating={isGenerating} /> </div> </main>
{/* Status Bar - Apple style */} <footer className="h-7 bg-[#28282a] border-t border-[#48484a] text-[#a1a1a6] text-xs flex items-center px-5 justify-between font-medium"> <div className="flex items-center space-x-5"> <span className="flex items-center space-x-1.5"> <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 16 16"> <path d="M8 0a8 8 0 1 1 0 16A8 8 0 0 1 8 0zM1.5 8a6.5 6.5 0 1 0 13 0 6.5 6.5 0 0 0-13 0z"/> </svg> <span>AnyCoder</span> </span> <span className="flex items-center space-x-1.5"> {isAuthenticated ? ( <> <span className="w-1.5 h-1.5 bg-[#30d158] rounded-full"></span> <span>Connected</span> </> ) : ( <> <span className="w-1.5 h-1.5 bg-[#ff9f0a] rounded-full"></span> <span>Not authenticated</span> </> )} </span> </div> <div className="flex items-center space-x-5"> <span>{messages.length} messages</span> <a href="https://huggingface.co/spaces/akhaliq/anycoder" target="_blank" rel="noopener noreferrer" className="hover:text-[#e5e5e7] transition-colors" > Built with anycoder </a> </div> </footer> </div> );}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119'use client';
import { useState, useRef, useEffect } from 'react';import type { Message } from '@/types';import ReactMarkdown from 'react-markdown';import remarkGfm from 'remark-gfm';
interface ChatInterfaceProps { messages: Message[]; onSendMessage: (message: string) => void; isGenerating: boolean; isAuthenticated?: boolean;}
export default function ChatInterface({ messages, onSendMessage, isGenerating, isAuthenticated = false }: ChatInterfaceProps) { const [input, setInput] = useState(''); const messagesEndRef = useRef<HTMLDivElement>(null);
const scrollToBottom = () => { messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' }); };
useEffect(() => { scrollToBottom(); }, [messages]);
const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); if (input.trim() && !isGenerating) { onSendMessage(input); setInput(''); } };
return ( <div className="flex flex-col h-full bg-[#1d1d1f]"> {/* Messages */} <div className="flex-1 overflow-y-auto p-5 space-y-4"> {messages.length === 0 ? ( <div className="text-center text-[#a1a1a6] mt-12"> <div className="text-5xl mb-5">π¬</div> {isAuthenticated ? ( <> <p className="text-lg font-semibold text-[#e5e5e7] tracking-tight">Start a conversation</p> <p className="text-sm mt-3 text-[#86868b] leading-relaxed">Describe what you want to build and I'll generate the code</p> </> ) : ( <> <p className="text-lg font-semibold text-[#ff9f0a]">π Sign in to get started</p> <p className="text-sm mt-3 text-[#86868b] leading-relaxed">Use Dev Login or sign in with Hugging Face</p> </> )} </div> ) : ( messages.map((message, index) => ( <div key={index} className={`flex ${message.role === 'user' ? 'justify-end' : 'justify-start'}`} > <div className={`max-w-[85%] rounded-2xl p-4 shadow-sm ${ message.role === 'user' ? 'bg-[#007aff] text-white' : 'bg-[#2c2c2e] text-[#e5e5e7] border border-[#48484a]' }`} > <div className="flex items-start space-x-3"> <div className="text-base flex-shrink-0"> {message.role === 'user' ? 'π€' : 'π€'} </div> <div className="flex-1 text-sm leading-relaxed"> {message.role === 'assistant' ? ( <ReactMarkdown remarkPlugins={[remarkGfm]} className="prose prose-invert prose-sm max-w-none" > {message.content} </ReactMarkdown> ) : ( <p className="whitespace-pre-wrap font-medium">{message.content}</p> )} </div> </div> {message.timestamp && ( <div className="text-xs opacity-50 mt-2 text-right font-medium"> {new Date(message.timestamp).toLocaleTimeString()} </div> )} </div> </div> )) )} <div ref={messagesEndRef} /> </div>
{/* Input */} <div className="border-t border-[#48484a] p-4 bg-[#28282a]"> <form onSubmit={handleSubmit} className="flex space-x-3"> <input type="text" value={input} onChange={(e) => setInput(e.target.value)} placeholder={isAuthenticated ? "Message AnyCoder..." : "π Please sign in first..."} disabled={isGenerating || !isAuthenticated} className="flex-1 px-4 py-3 bg-[#3a3a3c] text-[#e5e5e7] text-sm border border-[#48484a] rounded-xl focus:outline-none focus:ring-2 focus:ring-[#007aff] focus:border-transparent disabled:opacity-50 disabled:cursor-not-allowed placeholder-[#86868b] font-medium shadow-sm" /> <button type="submit" disabled={isGenerating || !input.trim() || !isAuthenticated} className="px-5 py-3 bg-[#007aff] text-white text-sm rounded-xl hover:bg-[#0051d5] disabled:bg-[#48484a] disabled:cursor-not-allowed transition-all font-semibold shadow-md disabled:shadow-none active:scale-95" > {isGenerating ? 'β³' : 'β'} </button> </form> </div> </div> );}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960'use client';
import { useEffect, useRef } from 'react';import Editor from '@monaco-editor/react';
interface CodeEditorProps { code: string; language: string; onChange?: (value: string) => void; readOnly?: boolean;}
export default function CodeEditor({ code, language, onChange, readOnly = false }: CodeEditorProps) { const editorRef = useRef<any>(null);
// Map our language names to Monaco language IDs const getMonacoLanguage = (lang: string): string => { const languageMap: Record<string, string> = { 'html': 'html', 'gradio': 'python', 'streamlit': 'python', 'transformers.js': 'javascript', 'react': 'typescript', 'comfyui': 'json', }; return languageMap[lang] || 'plaintext'; };
const handleEditorDidMount = (editor: any) => { editorRef.current = editor; };
return ( <div className="h-full overflow-hidden"> <Editor height="100%" language={getMonacoLanguage(language)} value={code} onChange={(value) => onChange && onChange(value || '')} theme="vs-dark" options={{ readOnly, minimap: { enabled: true }, fontSize: 14, fontFamily: "'SF Mono', 'JetBrains Mono', 'Menlo', 'Monaco', 'Courier New', monospace", wordWrap: 'on', lineNumbers: 'on', scrollBeyondLastLine: false, automaticLayout: true, tabSize: 2, padding: { top: 16, bottom: 16 }, lineHeight: 22, letterSpacing: 0.5, }} onMount={handleEditorDidMount} /> </div> );}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132'use client';
import { useState, useEffect } from 'react';import { apiClient } from '@/lib/api';import type { Model, Language } from '@/types';
interface ControlPanelProps { selectedLanguage: Language; selectedModel: string; onLanguageChange: (language: Language) => void; onModelChange: (modelId: string) => void; onDeploy: () => void; onClear: () => void; isGenerating: boolean;}
export default function ControlPanel({ selectedLanguage, selectedModel, onLanguageChange, onModelChange, onDeploy, onClear, isGenerating,}: ControlPanelProps) { const [models, setModels] = useState<Model[]>([]); const [languages, setLanguages] = useState<Language[]>([]);
useEffect(() => { loadModels(); loadLanguages(); }, []);
const loadModels = async () => { try { const modelsList = await apiClient.getModels(); setModels(modelsList); } catch (error) { console.error('Failed to load models:', error); } };
const loadLanguages = async () => { try { const { languages: languagesList } = await apiClient.getLanguages(); setLanguages(languagesList); } catch (error) { console.error('Failed to load languages:', error); } };
return ( <div className="bg-[#28282a] p-5 space-y-6 h-full"> <h3 className="text-base font-semibold text-[#e5e5e7] tracking-tight mb-2">Configuration</h3> {/* Language Selection */} <div> <label className="block text-sm font-semibold text-[#e5e5e7] mb-3 tracking-tight"> Language </label> <select value={selectedLanguage} onChange={(e) => onLanguageChange(e.target.value as Language)} disabled={isGenerating} className="w-full px-4 py-3 bg-[#3a3a3c] text-[#e5e5e7] text-sm border border-[#48484a] rounded-xl focus:outline-none focus:ring-2 focus:ring-[#007aff] focus:border-transparent disabled:opacity-50 font-medium shadow-sm" > {languages.map((lang) => ( <option key={lang} value={lang} className="bg-[#3a3a3c]"> {lang.charAt(0).toUpperCase() + lang.slice(1)} </option> ))} </select> </div>
{/* Model Selection */} <div> <label className="block text-sm font-semibold text-[#e5e5e7] mb-3 tracking-tight"> AI Model </label> <select value={selectedModel} onChange={(e) => onModelChange(e.target.value)} disabled={isGenerating} className="w-full px-4 py-3 bg-[#3a3a3c] text-[#e5e5e7] text-sm border border-[#48484a] rounded-xl focus:outline-none focus:ring-2 focus:ring-[#007aff] focus:border-transparent disabled:opacity-50 font-medium shadow-sm" > {models.map((model) => ( <option key={model.id} value={model.id} className="bg-[#3a3a3c]"> {model.name} </option> ))} </select> {models.find(m => m.id === selectedModel) && ( <p className="text-xs text-[#86868b] mt-3 leading-relaxed"> {models.find(m => m.id === selectedModel)?.description} </p> )} </div>
{/* Action Buttons */} <div className="flex flex-col space-y-3 pt-4"> <button onClick={onDeploy} disabled={isGenerating} className="w-full px-4 py-3.5 bg-[#007aff] text-white text-sm rounded-xl hover:bg-[#0051d5] disabled:opacity-50 disabled:cursor-not-allowed transition-all font-semibold flex items-center justify-center space-x-2 shadow-md active:scale-95" > <span>π</span> <span>Deploy</span> </button> <button onClick={onClear} disabled={isGenerating} className="w-full px-4 py-3.5 bg-[#3a3a3c] text-[#e5e5e7] text-sm rounded-xl hover:bg-[#48484a] disabled:opacity-50 disabled:cursor-not-allowed transition-all font-semibold border border-[#48484a] flex items-center justify-center space-x-2 shadow-sm active:scale-95" > <span>ποΈ</span> <span>Clear</span> </button> </div>
{/* Info Panel */} <div className="mt-6 p-4 bg-[#2c2c2e] border border-[#48484a] rounded-xl shadow-sm"> <h4 className="text-sm font-semibold text-[#e5e5e7] mb-3 tracking-tight">π‘ Tips</h4> <ul className="text-xs text-[#86868b] space-y-2 leading-relaxed"> <li>β’ Be specific in your requirements</li> <li>β’ Try different AI models</li> <li>β’ Edit code in the editor</li> <li>β’ Deploy to HF Spaces</li> </ul> </div> </div> );}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179'use client';
import { useState, useEffect } from 'react';import { initializeOAuth, loginWithHuggingFace, loginDevMode, logout, getStoredUserInfo, isAuthenticated, isDevelopmentMode } from '@/lib/auth';import { apiClient } from '@/lib/api';import type { OAuthUserInfo } from '@/lib/auth';
export default function Header() { const [userInfo, setUserInfo] = useState<OAuthUserInfo | null>(null); const [isLoading, setIsLoading] = useState(true); const [showDevLogin, setShowDevLogin] = useState(false); const [devUsername, setDevUsername] = useState(''); const isDevMode = isDevelopmentMode();
useEffect(() => { handleOAuthInit(); }, []);
const handleOAuthInit = async () => { setIsLoading(true); try { const oauthResult = await initializeOAuth(); if (oauthResult) { setUserInfo(oauthResult.userInfo); // Set token in API client apiClient.setToken(oauthResult.accessToken); } else { // Check if we have stored user info const storedUserInfo = getStoredUserInfo(); if (storedUserInfo) { setUserInfo(storedUserInfo); } } } catch (error) { console.error('OAuth initialization error:', error); } finally { setIsLoading(false); } };
const handleLogin = async () => { try { await loginWithHuggingFace(); } catch (error) { console.error('Login failed:', error); alert('Failed to start login process. Please try again.'); } };
const handleLogout = () => { logout(); apiClient.logout(); setUserInfo(null); // Reload page to clear state window.location.reload(); };
const handleDevLogin = () => { if (!devUsername.trim()) { alert('Please enter a username'); return; } try { const result = loginDevMode(devUsername); setUserInfo(result.userInfo); apiClient.setToken(result.accessToken); setShowDevLogin(false); setDevUsername(''); } catch (error) { console.error('Dev login failed:', error); alert('Failed to login in dev mode'); } };
return ( <header className="bg-[#28282a] text-white border-b border-[#48484a]"> <div className="flex items-center justify-between px-5 h-14"> <div className="flex items-center space-x-3"> <div className="text-2xl">π</div> <h1 className="text-base font-semibold text-[#e5e5e7] tracking-tight">AnyCoder</h1> </div> <div className="flex items-center space-x-4"> {isLoading ? ( <div className="px-4 py-2"> <span className="text-xs text-[#86868b] font-medium">Loading...</span> </div> ) : userInfo ? ( <div className="flex items-center space-x-3"> {userInfo.avatarUrl && ( <img src={userInfo.avatarUrl} alt={userInfo.name} className="w-7 h-7 rounded-full ring-2 ring-[#48484a]" /> )} <span className="text-sm text-[#e5e5e7] font-medium"> {userInfo.preferredUsername || userInfo.name} </span> <button onClick={handleLogout} className="px-4 py-2 bg-[#3a3a3c] text-[#e5e5e7] text-xs rounded-lg hover:bg-[#48484a] transition-all border border-[#48484a] font-semibold shadow-sm active:scale-95" > Logout </button> </div> ) : ( <div className="flex items-center space-x-3"> {/* Dev Mode Login (only on localhost) */} {isDevMode && ( <> {showDevLogin ? ( <div className="flex items-center space-x-2 bg-[#3a3a3c] px-3 py-2 rounded-lg border border-[#ff9f0a] shadow-lg"> <span className="text-xs text-[#ff9f0a] font-semibold">DEV</span> <input type="text" value={devUsername} onChange={(e) => setDevUsername(e.target.value)} onKeyPress={(e) => e.key === 'Enter' && handleDevLogin()} placeholder="username" className="px-3 py-1.5 rounded-lg text-xs bg-[#2c2c2e] text-[#e5e5e7] border border-[#48484a] focus:outline-none focus:ring-2 focus:ring-[#ff9f0a] focus:border-transparent w-28 font-medium" autoFocus /> <button onClick={handleDevLogin} className="px-3 py-1.5 bg-[#ff9f0a] text-white rounded-lg hover:bg-[#ff8800] text-xs font-semibold shadow-sm active:scale-95" > OK </button> <button onClick={() => { setShowDevLogin(false); setDevUsername(''); }} className="text-[#86868b] hover:text-[#e5e5e7] text-sm transition-colors" > β </button> </div> ) : ( <button onClick={() => setShowDevLogin(true)} className="px-4 py-2 bg-[#ff9f0a] text-white rounded-lg hover:bg-[#ff8800] transition-all text-xs flex items-center space-x-2 font-semibold shadow-sm active:scale-95" title="Dev Mode (localhost)" > <span>π§</span> <span>Dev Login</span> </button> )} <span className="text-[#86868b] text-xs font-medium">or</span> </> )} {/* OAuth Login */} <button onClick={handleLogin} className="px-4 py-2 bg-[#007aff] text-white rounded-lg hover:bg-[#0051d5] transition-all text-xs flex items-center space-x-2 font-semibold shadow-md active:scale-95" > <span>π€</span> <span>Sign in</span> </button> </div> )} </div> </div> </header> );}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960// Type definitions for AnyCoder frontend
export interface Model { name: string; id: string; description: string;}
export interface Message { role: 'user' | 'assistant' | 'system'; content: string; timestamp?: string;}
export interface CodeGenerationRequest { query: string; language: string; model_id: string; provider: string; history: string[][]; agent_mode: boolean;}
export interface CodeGenerationResponse { code: string; history: string[][]; status: string;}
export interface StreamChunk { type: 'chunk' | 'complete' | 'error' | 'status'; content?: string; code?: string; message?: string; progress?: number; timestamp?: string;}
export interface AuthStatus { authenticated: boolean; username?: string; message: string;}
export interface DeploymentRequest { code: string; space_name?: string; language: string; requirements?: string;}
export interface DeploymentResponse { success: boolean; space_url?: string; message: string; dev_mode?: boolean;}
export type Language = 'html' | 'gradio' | 'transformers.js' | 'streamlit' | 'comfyui' | 'react';
1234567891011121314151617181920212223242526272829/** @type {import('tailwindcss').Config} */module.exports = { content: [ './src/pages/**/*.{js,ts,jsx,tsx,mdx}', './src/components/**/*.{js,ts,jsx,tsx,mdx}', './src/app/**/*.{js,ts,jsx,tsx,mdx}', ], theme: { extend: { colors: { primary: { 50: '#eff6ff', 100: '#dbeafe', 200: '#bfdbfe', 300: '#93c5fd', 400: '#60a5fa', 500: '#3b82f6', 600: '#2563eb', 700: '#1d4ed8', 800: '#1e40af', 900: '#1e3a8a', }, }, }, }, plugins: [], darkMode: 'class',}
123456789101112131415161718192021222324252627{ "compilerOptions": { "lib": ["dom", "dom.iterable", "esnext"], "allowJs": true, "skipLibCheck": true, "strict": true, "noEmit": true, "esModuleInterop": true, "module": "esnext", "moduleResolution": "bundler", "resolveJsonModule": true, "isolatedModules": true, "jsx": "preserve", "incremental": true, "plugins": [ { "name": "next" } ], "paths": { "@/*": ["./src/*"] } }, "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"], "exclude": ["node_modules"]}
123456789101112131415161718192021#!/bin/bash# Start the FastAPI backend
echo "Starting AnyCoder FastAPI Backend..."echo "API will be available at: http://localhost:8000"echo "API docs at: http://localhost:8000/docs"echo ""
# Check if HF_TOKEN is setif [ -z "$HF_TOKEN" ]; then echo "β οΈ WARNING: HF_TOKEN environment variable is not set!" echo "Please set it with: export HF_TOKEN=your_token_here" echo ""fi
# Activate virtual environmentsource /Users/ahsenkhaliq/anycoder/.venv/bin/activate
# Start the backendpython backend_api.py
123456789101112131415161718#!/bin/bash# Start the Next.js frontend
echo "Starting AnyCoder Frontend..."echo "Frontend will be available at: http://localhost:3000"echo ""
cd frontend
# Install dependencies if node_modules doesn't existif [ ! -d "node_modules" ]; then echo "Installing dependencies..." npm installfi
# Start the development servernpm run dev
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253#!/bin/bash# Start both backend and frontend in separate terminal windows
echo "π Starting AnyCoder Full-Stack Application..."echo ""
# Function to check if a command existscommand_exists() { command -v "$1" >/dev/null 2>&1}
# Check for required toolsif ! command_exists python3; then echo "β Python 3 is not installed" exit 1fi
if ! command_exists node; then echo "β Node.js is not installed" exit 1fi
# Make scripts executablechmod +x start_backend.shchmod +x start_frontend.sh
echo "π¦ Starting Backend..."# Start backend in background with venv activated(source /Users/ahsenkhaliq/anycoder/.venv/bin/activate && python backend_api.py) &BACKEND_PID=$!
# Wait for backend to startsleep 3
echo ""echo "π¨ Starting Frontend..."# Start frontend in background./start_frontend.sh &FRONTEND_PID=$!
echo ""echo "β
Full-stack application started!"echo ""echo "π Backend API: http://localhost:8000"echo "π API Docs: http://localhost:8000/docs"echo "π Frontend: http://localhost:3000"echo ""echo "Press Ctrl+C to stop both services"
# Wait for Ctrl+Ctrap "kill $BACKEND_PID $FRONTEND_PID; exit" INTwait
.dockerignoreAdded+67
DockerfileAdded+91
README.md+99-107
README_GRADIO.mdAdded+145
backend_api.pyAdded+499
frontend/.gitignoreAdded+35
frontend/next.config.jsAdded+26
frontend/package-lock.jsonAdded
frontend/package.jsonAdded+35
frontend/postcss.config.jsAdded+7
frontend/src/app/globals.cssAdded+114
frontend/src/app/layout.tsxAdded+23
frontend/src/app/page.tsxAdded+278
frontend/src/components/ChatInterface.tsxAdded+119
frontend/src/components/CodeEditor.tsxAdded+60
frontend/src/components/ControlPanel.tsxAdded+132
frontend/src/components/Header.tsxAdded+179
frontend/src/types/index.tsAdded+60
frontend/tailwind.config.jsAdded+29
frontend/tsconfig.jsonAdded+27
start_backend.shAdded+21
start_frontend.shAdded+18
start_fullstack.shAdded+53