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
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
---
title: LLM Code Deployment API
emoji: πŸš€
colorFrom: blue
colorTo: green
sdk: docker
app_port: 7860
---

# LLM Code Deployment System

An automated system for building, deploying, and evaluating LLM-generated web applications with GitHub Pages integration.

## Overview

This project implements a complete workflow for:
- **Students**: Receive task requests, use LLMs to generate code, deploy to GitHub Pages, and submit for evaluation
- **Instructors**: Generate task requests, receive submissions, run automated evaluations (static, dynamic, and LLM-based)

## πŸš€ Quick Deployment for Students

**Deploy to Hugging Face Spaces in 10 minutes:**

1. Read **[DEPLOYMENT.md](DEPLOYMENT.md)** for complete step-by-step instructions
2. Read **[README_SPACES.md](README_SPACES.md)** for Hugging Face Spaces configuration
3. Get your AIPipe token from https://aipipe.org/login ($2/month free for IIT Madras students)
4. Create a Space at https://huggingface.co/new-space
5. Configure environment variables and deploy!

**Already deployed?** Just submit your endpoint URL to the instructor's Google Form!

## Architecture

```
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Instructor β”‚         β”‚   Student    β”‚         β”‚   GitHub    β”‚
β”‚   System    │────────▢│     API      │────────▢│    Pages    β”‚
β”‚             β”‚  POST   β”‚              β”‚  Deploy β”‚             β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  Task   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
      β”‚                        β”‚                         β”‚
      β”‚                        β”‚                         β”‚
      β”‚                        └────────POSTβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
      β”‚                         Submission               β”‚
      β”‚                                                  β”‚
      β–Ό                                                  β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”                                   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Evaluation │◀──────────────────────────────────│  Validation β”‚
β”‚   Database  β”‚                                   β”‚   & Checks  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜                                   β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
```

## Features

### Student-Side
- **API Endpoint**: Receives task requests via HTTP POST
- **LLM Code Generation**: Uses Claude/GPT to generate complete web apps
- **GitHub Integration**: Automatically creates repos, pushes code, enables Pages
- **Automatic Notification**: Sends repo details to evaluation endpoint
- **Round 2 Support**: Handles update requests for existing repos

### Instructor-Side
- **Task Templates**: YAML-based parametrizable task definitions
- **Round 1 & 2 Scripts**: Automated task generation and distribution
- **Evaluation API**: Receives and validates student submissions
- **Multi-Level Checks**:
  - Static: License, README, repo creation time, secrets detection
  - LLM: Code quality, documentation quality
  - Dynamic: Playwright-based functional testing
- **Database**: PostgreSQL storage for tasks, repos, and results

## Project Structure

```
tds-p1/
β”œβ”€β”€ shared/                 # Shared utilities and models
β”‚   β”œβ”€β”€ config.py          # Configuration management
β”‚   β”œβ”€β”€ models.py          # Pydantic data models
β”‚   β”œβ”€β”€ logger.py          # Logging setup
β”‚   └── utils.py           # Utility functions
β”œβ”€β”€ student/               # Student-side components
β”‚   β”œβ”€β”€ api.py             # FastAPI endpoint
β”‚   β”œβ”€β”€ code_generator.py  # LLM-based code generation
β”‚   β”œβ”€β”€ github_manager.py  # GitHub operations
β”‚   └── notification_client.py  # Evaluation notification
β”œβ”€β”€ instructor/            # Instructor-side components
β”‚   β”œβ”€β”€ api.py             # Evaluation endpoint
β”‚   β”œβ”€β”€ database.py        # Database models and operations
β”‚   β”œβ”€β”€ task_templates.py  # Template management
β”‚   β”œβ”€β”€ round1.py          # Round 1 task generation
β”‚   β”œβ”€β”€ round2.py          # Round 2 task generation
β”‚   β”œβ”€β”€ evaluate.py        # Main evaluation script
β”‚   └── checks/            # Evaluation modules
β”‚       β”œβ”€β”€ static_checks.py   # Static analysis
β”‚       β”œβ”€β”€ dynamic_checks.py  # Playwright tests
β”‚       └── llm_checks.py      # LLM evaluations
β”œβ”€β”€ templates/             # Task template YAML files
β”‚   β”œβ”€β”€ sum-of-sales.yaml
β”‚   β”œβ”€β”€ markdown-to-html.yaml
β”‚   └── github-user-created.yaml
β”œβ”€β”€ pyproject.toml         # Project dependencies
β”œβ”€β”€ .env.example           # Environment variables template
└── README.md              # This file
```

## Setup

### Prerequisites
- Python 3.10+
- PostgreSQL database
- GitHub account with personal access token
- Anthropic or OpenAI API key

### Installation

1. **Clone the repository**
```bash
git clone <your-repo-url>
cd tds-p1
```

2. **Install dependencies**
```bash
pip install -e .
```

3. **Install Playwright browsers**
```bash
playwright install chromium
```

4. **Configure environment**
```bash
cp .env.example .env
# Edit .env with your credentials
```

5. **Set up database**
```bash
# Create PostgreSQL database
createdb llm_deployment

# Initialize tables
python -c "from instructor.database import Database; Database().create_tables()"
```

## Configuration

Edit `.env` with your settings:

### Student Configuration
```bash
STUDENT_SECRET=your-secret-key
STUDENT_EMAIL=your-email@example.com
STUDENT_API_PORT=8000
```

### GitHub
```bash
GITHUB_TOKEN=ghp_your_personal_access_token
GITHUB_USERNAME=your-username
```

### LLM Provider
```bash
# Choose one
LLM_PROVIDER=anthropic  # or openai
ANTHROPIC_API_KEY=sk-ant-...
# OR
OPENAI_API_KEY=sk-...
LLM_MODEL=claude-3-5-sonnet-20241022
```

### Instructor
```bash
DATABASE_URL=postgresql://user:password@localhost:5432/llm_deployment
EVALUATION_API_URL=http://your-server:8001/api/evaluate
```

## Usage

### For Students

1. **Start the Student API**
```bash
python -m student.api
```

The API will listen on `http://localhost:8000/api/build`

2. **Test with a sample request**
```bash
curl -X POST http://localhost:8000/api/build \
  -H "Content-Type: application/json" \
  -d '{
    "email": "your-email@example.com",
    "secret": "your-secret",
    "task": "test-task-abc",
    "round": 1,
    "nonce": "unique-nonce-123",
    "brief": "Create a simple Hello World page",
    "checks": ["Page displays Hello World"],
    "evaluation_url": "http://localhost:8001/api/evaluate",
    "attachments": []
  }'
```

### For Instructors

1. **Start the Evaluation API**
```bash
python -m instructor.api
```

2. **Prepare submissions.csv**
```csv
timestamp,email,endpoint,secret
2025-01-15T10:00:00,student1@example.com,http://student1.com/api/build,secret1
2025-01-15T10:05:00,student2@example.com,http://student2.com/api/build,secret2
```

3. **Run Round 1 task generation**
```bash
python -m instructor.round1
```

This will:
- Load submissions from CSV
- Generate unique tasks from templates
- POST tasks to student endpoints
- Log results to database

4. **Run evaluations**
```bash
python -m instructor.evaluate
```

This will:
- Fetch pending submissions
- Clone repositories
- Run static, LLM, and Playwright checks
- Save results to database

5. **Run Round 2 task generation**
```bash
python -m instructor.round2
```

This will:
- Find all Round 1 submissions
- Generate Round 2 update tasks
- POST to student endpoints

## Task Templates

Task templates are YAML files in the `templates/` directory. Example:

```yaml
id: sum-of-sales
brief: Publish a single-page site that fetches data.csv from attachments...
attachments:
  - name: data.csv
    url: data:text/csv;base64,placeholder
checks:
  - "Page title equals 'Sales Summary {{ seed }}'"
  - "Bootstrap 5 CSS loaded from jsdelivr"
round2:
  - brief: Add a Bootstrap table #product-sales...
    checks:
      - "Table #product-sales exists"
```

### Template Variables
- `{{ seed }}`: Unique seed based on email and timestamp
- `{{ hash }}`: Deterministic hash value
- `{{ result }}`: Generated numeric value

## API Endpoints

### Student API

**POST /api/build**
- Receives task request
- Returns 200 on acceptance
- Processes in background

**GET /api/status/{task_id}**
- Returns task status

**GET /health**
- Health check

### Instructor API

**POST /api/evaluate**
- Receives repo submission
- Validates against task record
- Returns 200 on success

**GET /api/submissions/{email}**
- Returns all submissions for email

**GET /api/results/{email}**
- Returns all evaluation results

## Evaluation Criteria

### Static Checks
- βœ“ Repository created after task sent
- βœ“ MIT LICENSE exists in root
- βœ“ README.md present with good structure
- βœ“ No secrets in git history

### LLM Checks
- βœ“ README.md professional quality (0-1 score)
- βœ“ Code quality and best practices (0-1 score)

### Dynamic Checks
- βœ“ Task-specific requirements (from template)
- βœ“ Page loads successfully
- βœ“ JavaScript evaluations
- βœ“ Element presence and content

## Database Schema

### Tasks Table
- Task requests sent to students
- Fields: email, task, round, nonce, brief, checks, etc.

### Repos Table
- Repository submissions from students
- Fields: email, task, round, repo_url, commit_sha, pages_url

### Results Table
- Evaluation results
- Fields: email, task, round, check, score, reason, logs

## Troubleshooting

### Common Issues

**Student API not receiving requests**
- Check firewall settings
- Ensure port 8000 is accessible
- Verify endpoint URL in submissions.csv

**GitHub Pages not deploying**
- Verify GITHUB_TOKEN has repo permissions
- Check repository is public
- Wait up to 60 seconds for Pages to activate

**LLM generation fails**
- Check API key is valid
- Verify API quota/credits
- Review logs for error details

**Playwright tests fail**
- Ensure chromium is installed: `playwright install chromium`
- Check Pages URL is accessible
- Increase timeout if needed

**Database connection errors**
- Verify PostgreSQL is running
- Check DATABASE_URL credentials
- Ensure database exists

## Development

### Running Tests
```bash
pytest tests/
```

### Code Formatting
```bash
black .
ruff check .
```

### Type Checking
```bash
mypy .
```

## License

MIT License

Copyright (c) 2025

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

## Contributing

1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Submit a pull request

## Support

For issues and questions:
- Check the troubleshooting section
- Review logs in `logs/app.log`
- Open an issue on GitHub