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
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
# Deployment Guide

## Quick Deployment Options

### Option 1: Replit (Easiest - FREE)

1. **Create Account**: https://replit.com/signup
2. **Create New Project**: Click "Create" β†’ "Import from GitHub"
3. **Enter Repository URL**: Paste your GitHub repo URL
4. **Deploy**:
   ```bash
   pip install -r requirements.txt
   python web/app.py
   ```
5. **Access**: Replit will provide a live URL (e.g., `https://project-name.replit.dev`)

### Option 2: Railway (FREE tier available)

1. **Create Account**: https://railway.app
2. **Connect Repository**: Click "Create Project" β†’ "Deploy from GitHub"
3. **Select Your Repo**: Choose the AI code generation repo
4. **Add Environment Variables** (if using LLM):
   - Key: `ANTHROPIC_API_KEY`
   - Value: Your API key
5. **Deploy**: Railway auto-deploys on push
6. **Get URL**: Check "Deployments" for live URL

### Option 3: Heroku (Paid but easy)

1. **Create Account**: https://heroku.com
2. **Install Heroku CLI**: https://devcenter.heroku.com/articles/heroku-cli
3. **Create App**:
   ```bash
   heroku login
   heroku create your-app-name
   ```
4. **Deploy**:
   ```bash
   git push heroku main
   ```
5. **Get URL**: `https://your-app-name.herokuapp.com`

### Option 4: Google Cloud Run (Pay-per-use)

1. **Setup**:
   ```bash
   gcloud auth login
   gcloud config set project your-project-id
   ```

2. **Create Dockerfile**:
   ```dockerfile
   FROM python:3.9-slim
   WORKDIR /app
   COPY . .
   RUN pip install -r requirements.txt
   EXPOSE 5000
   CMD ["python", "web/app.py"]
   ```

3. **Deploy**:
   ```bash
   gcloud run deploy code-gen \
     --source . \
     --platform managed \
     --region us-central1
   ```

4. **Get URL**: GCP will provide a live URL

---

## Local Deployment (for testing)

### Prerequisites
- Python 3.8+
- Git

### Steps

1. **Clone Repository**
   ```bash
   git clone https://github.com/your-username/ai-code-gen.git
   cd ai-code-gen
   ```

2. **Install Dependencies**
   ```bash
   pip install -r requirements.txt
   ```

3. **Set Environment Variables** (Optional)
   ```bash
   export ANTHROPIC_API_KEY="your-api-key"  # For LLM features
   ```

4. **Run Server**
   ```bash
   python web/app.py
   ```

5. **Access**
   ```
   http://localhost:5000
   ```

---

## Production Deployment (Best Practices)

### 1. Use Gunicorn

```bash
pip install gunicorn
gunicorn -w 4 -b 0.0.0.0:8000 web.app
```

### 2. Use Environment Variables

Create `.env` file:
```
ANTHROPIC_API_KEY=your-key
FLASK_ENV=production
```

### 3. Add SSL/HTTPS

Use a reverse proxy (Nginx, Cloudflare)

### 4. Enable Logging

```python
# In web/app.py
import logging
logging.basicConfig(level=logging.INFO)
```

### 5. Add Rate Limiting

```python
from flask_limiter import Limiter
from flask_limiter.util import get_remote_address

limiter = Limiter(
    app=app,
    key_func=get_remote_address,
    default_limits=["200 per day", "50 per hour"]
)
```

---

## Docker Deployment

### Dockerfile

```dockerfile
FROM python:3.9-slim

WORKDIR /app

# Copy requirements and install
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt

# Copy application
COPY . .

# Expose port
EXPOSE 5000

# Run with gunicorn for production
CMD ["gunicorn", "-w", "4", "-b", "0.0.0.0:5000", "web.app"]
```

### Build and Run

```bash
# Build image
docker build -t code-gen:latest .

# Run container
docker run -p 5000:5000 code-gen:latest

# Access
open http://localhost:5000
```

### Docker Compose

```yaml
version: '3.8'

services:
  web:
    build: .
    ports:
      - "5000:5000"
    environment:
      - ANTHROPIC_API_KEY=${ANTHROPIC_API_KEY}
    restart: unless-stopped
```

Run with:
```bash
docker-compose up
```

---

## Monitoring & Logging

### Application Logging

```python
import logging

logger = logging.getLogger(__name__)

@app.route('/api/generate', methods=['POST'])
def generate():
    logger.info("Generation request received")
    try:
        # ... generation code ...
        logger.info("Generation successful")
    except Exception as e:
        logger.error(f"Generation failed: {e}")
    
    return jsonify(...)
```

### Health Check

The API includes a health endpoint:
```bash
curl https://your-app.com/api/health
```

Returns:
```json
{
  "status": "healthy",
  "timestamp": "2026-05-06T07:52:40.123456",
  "total_requests": 42
}
```

---

## Performance Optimization

### 1. Enable Caching

```python
from functools import lru_cache

@lru_cache(maxsize=128)
def extract_intent(prompt):
    # Intent extraction is cached
    return ...
```

### 2. Use Connection Pooling

```python
# For database connections (future)
pool = create_engine(
    'postgresql://...',
    poolclass=StaticPool,
    pool_size=20
)
```

### 3. Enable Compression

```python
from flask_compress import Compress
Compress(app)
```

### 4. Use CDN

Deploy static files to CDN (Cloudflare, AWS CloudFront)

---

## Troubleshooting

### Port Already in Use

```bash
# Windows
netstat -ano | findstr :5000
taskkill /PID <PID> /F

# Linux/Mac
lsof -i :5000
kill -9 <PID>
```

### Module Not Found

```bash
pip install --upgrade pip
pip install -r requirements.txt
```

### API Timeout

Increase timeout in production:
```python
app.config['REQUEST_TIMEOUT'] = 60  # seconds
```

### Memory Issues

Use rule-based generation:
```python
pipeline = Pipeline(use_llm=False)  # Lower memory usage
```

---

## Continuous Deployment (CD)

### GitHub Actions

Create `.github/workflows/deploy.yml`:

```yaml
name: Deploy

on:
  push:
    branches: [main]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/setup-python@v2
        with:
          python-version: 3.9
      - run: pip install -r requirements.txt
      - run: pytest  # If tests exist
      - uses: AkhileshNS/heroku-deploy@v3.12.12
        with:
          heroku_api_key: ${{secrets.HEROKU_API_KEY}}
          heroku_app_name: "your-app-name"
          heroku_email: "your-email@example.com"
```

### Push to Deploy

```bash
git push origin main
# Automatically deploys!
```

---

## Monitoring Checklist

- [ ] Health endpoint working
- [ ] Error logging enabled
- [ ] Performance monitored
- [ ] API rate limits set
- [ ] SSL/HTTPS enabled (production)
- [ ] Environment variables secured
- [ ] Backups configured
- [ ] Alerts setup

---

## Cost Estimates

| Platform | Free Tier | Paid Tier |
|----------|-----------|-----------|
| Replit | βœ… Yes | $7/mo |
| Railway | βœ… Yes (10 GB) | $5/mo+ |
| Heroku | βœ… (limited) | $7-50/mo |
| Google Cloud Run | βœ… ($11 free) | $0.00002/req |
| Vercel | βœ… (serverless) | $20/mo |

**Recommendation**: Start with Replit (free, easiest)

---

## Live URL Examples

After deployment, you'll have URLs like:
- Replit: `https://ai-code-gen.replit.dev`
- Railway: `https://ai-code-gen-production.up.railway.app`
- Heroku: `https://ai-code-gen.herokuapp.com`
- Cloud Run: `https://code-gen-xyz.run.app`

---

## Testing Live Deployment

```bash
# Test health
curl https://your-app-url/api/health

# Test generation
curl -X POST https://your-app-url/api/generate \
  -H "Content-Type: application/json" \
  -d '{"prompt":"Build a todo app"}'

# Test example
curl https://your-app-url/api/example
```

---

## Support

For deployment issues:
1. Check platform-specific documentation
2. Review application logs
3. Test locally first
4. Use health endpoint for diagnostics

---

*Choose your deployment platform and go live! πŸš€*