mrsavage1 commited on
Commit
90b617f
·
verified ·
1 Parent(s): ec77f00

Upload 14 files

Browse files
Files changed (14) hide show
  1. .gitattributes +35 -35
  2. CHECKLIST.txt +48 -48
  3. DEPLOY.txt +33 -33
  4. DEPLOYMENT.md +166 -166
  5. Dockerfile +10 -10
  6. GITHUB_DEPLOYMENT_GUIDE.md +542 -0
  7. IMPROVEMENTS.md +376 -376
  8. QUICK_SETUP.md +75 -0
  9. README.md +234 -234
  10. STATUS.txt +58 -58
  11. app.py +0 -0
  12. github_deploy.py +937 -0
  13. hf-mofh-api.php +128 -128
  14. requirements.txt +8 -5
.gitattributes CHANGED
@@ -1,35 +1,35 @@
1
- *.7z filter=lfs diff=lfs merge=lfs -text
2
- *.arrow filter=lfs diff=lfs merge=lfs -text
3
- *.bin filter=lfs diff=lfs merge=lfs -text
4
- *.bz2 filter=lfs diff=lfs merge=lfs -text
5
- *.ckpt filter=lfs diff=lfs merge=lfs -text
6
- *.ftz filter=lfs diff=lfs merge=lfs -text
7
- *.gz filter=lfs diff=lfs merge=lfs -text
8
- *.h5 filter=lfs diff=lfs merge=lfs -text
9
- *.joblib filter=lfs diff=lfs merge=lfs -text
10
- *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
- *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
- *.model filter=lfs diff=lfs merge=lfs -text
13
- *.msgpack filter=lfs diff=lfs merge=lfs -text
14
- *.npy filter=lfs diff=lfs merge=lfs -text
15
- *.npz filter=lfs diff=lfs merge=lfs -text
16
- *.onnx filter=lfs diff=lfs merge=lfs -text
17
- *.ot filter=lfs diff=lfs merge=lfs -text
18
- *.parquet filter=lfs diff=lfs merge=lfs -text
19
- *.pb filter=lfs diff=lfs merge=lfs -text
20
- *.pickle filter=lfs diff=lfs merge=lfs -text
21
- *.pkl filter=lfs diff=lfs merge=lfs -text
22
- *.pt filter=lfs diff=lfs merge=lfs -text
23
- *.pth filter=lfs diff=lfs merge=lfs -text
24
- *.rar filter=lfs diff=lfs merge=lfs -text
25
- *.safetensors filter=lfs diff=lfs merge=lfs -text
26
- saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
- *.tar.* filter=lfs diff=lfs merge=lfs -text
28
- *.tar filter=lfs diff=lfs merge=lfs -text
29
- *.tflite filter=lfs diff=lfs merge=lfs -text
30
- *.tgz filter=lfs diff=lfs merge=lfs -text
31
- *.wasm filter=lfs diff=lfs merge=lfs -text
32
- *.xz filter=lfs diff=lfs merge=lfs -text
33
- *.zip filter=lfs diff=lfs merge=lfs -text
34
- *.zst filter=lfs diff=lfs merge=lfs -text
35
- *tfevents* filter=lfs diff=lfs merge=lfs -text
 
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
CHECKLIST.txt CHANGED
@@ -1,48 +1,48 @@
1
- FINAL DEPLOYMENT CHECKLIST
2
- ==========================
3
-
4
- PRE-DEPLOYMENT TESTS:
5
- ✓ Python syntax check - PASSED
6
- ✓ App imports successfully - PASSED
7
- ✓ All 11 endpoints registered - PASSED
8
- ✓ API key rotation working - PASSED
9
- ✓ Model selection working - PASSED
10
- ✓ Dependencies installed - PASSED
11
- ✓ File sizes reasonable - PASSED
12
- ✓ No syntax errors - PASSED
13
- ✓ No import errors - PASSED
14
-
15
- FILES TO UPLOAD (6):
16
- ✓ app.py (51 KB)
17
- ✓ requirements.txt (0.09 KB)
18
- ✓ Dockerfile (0.24 KB)
19
- ✓ README.md (4.6 KB)
20
- ✓ DEPLOY.txt (0.87 KB)
21
- ✓ STATUS.txt (1.67 KB)
22
-
23
- DEPLOYMENT STEPS:
24
- 1. Go to https://huggingface.co/spaces
25
- 2. Click "Create new Space"
26
- 3. Name: iona-ai
27
- 4. SDK: Docker
28
- 5. Upload all 6 files
29
- 6. Wait 2-3 minutes for deployment
30
- 7. Visit your space URL
31
- 8. Copy External IP from dashboard
32
- 9. Add IP to MOFH whitelist at panel.myownfreehost.net
33
- 10. Update createwith-iona-ai.php line 33:
34
- define('HF_SPACE_URL', 'https://YOUR-USERNAME-iona-ai.hf.space');
35
-
36
- POST-DEPLOYMENT VERIFICATION:
37
- 1. Visit https://YOUR-SPACE.hf.space/
38
- 2. Check dashboard loads
39
- 3. Test /health endpoint
40
- 4. Test /test endpoint
41
- 5. Try generating a simple website
42
- 6. Verify MOFH account creation works
43
-
44
- READY TO DEPLOY: YES ✓
45
- ALL TESTS PASSED: YES ✓
46
- NO ISSUES FOUND: YES ✓
47
-
48
- DEPLOY NOW! 🚀
 
1
+ FINAL DEPLOYMENT CHECKLIST
2
+ ==========================
3
+
4
+ PRE-DEPLOYMENT TESTS:
5
+ ✓ Python syntax check - PASSED
6
+ ✓ App imports successfully - PASSED
7
+ ✓ All 11 endpoints registered - PASSED
8
+ ✓ API key rotation working - PASSED
9
+ ✓ Model selection working - PASSED
10
+ ✓ Dependencies installed - PASSED
11
+ ✓ File sizes reasonable - PASSED
12
+ ✓ No syntax errors - PASSED
13
+ ✓ No import errors - PASSED
14
+
15
+ FILES TO UPLOAD (6):
16
+ ✓ app.py (51 KB)
17
+ ✓ requirements.txt (0.09 KB)
18
+ ✓ Dockerfile (0.24 KB)
19
+ ✓ README.md (4.6 KB)
20
+ ✓ DEPLOY.txt (0.87 KB)
21
+ ✓ STATUS.txt (1.67 KB)
22
+
23
+ DEPLOYMENT STEPS:
24
+ 1. Go to https://huggingface.co/spaces
25
+ 2. Click "Create new Space"
26
+ 3. Name: iona-ai
27
+ 4. SDK: Docker
28
+ 5. Upload all 6 files
29
+ 6. Wait 2-3 minutes for deployment
30
+ 7. Visit your space URL
31
+ 8. Copy External IP from dashboard
32
+ 9. Add IP to MOFH whitelist at panel.myownfreehost.net
33
+ 10. Update createwith-iona-ai.php line 33:
34
+ define('HF_SPACE_URL', 'https://YOUR-USERNAME-iona-ai.hf.space');
35
+
36
+ POST-DEPLOYMENT VERIFICATION:
37
+ 1. Visit https://YOUR-SPACE.hf.space/
38
+ 2. Check dashboard loads
39
+ 3. Test /health endpoint
40
+ 4. Test /test endpoint
41
+ 5. Try generating a simple website
42
+ 6. Verify MOFH account creation works
43
+
44
+ READY TO DEPLOY: YES ✓
45
+ ALL TESTS PASSED: YES ✓
46
+ NO ISSUES FOUND: YES ✓
47
+
48
+ DEPLOY NOW! 🚀
DEPLOY.txt CHANGED
@@ -1,33 +1,33 @@
1
- IONA AI - Hugging Face Deployment Instructions
2
- ==============================================
3
-
4
- READY TO DEPLOY! ✓
5
-
6
- Files Needed:
7
- - app.py (Main application)
8
- - requirements.txt (Dependencies)
9
- - Dockerfile (Container config)
10
- - README.md (Documentation)
11
-
12
- Quick Deploy to Hugging Face:
13
- 1. Go to https://huggingface.co/spaces
14
- 2. Click "Create new Space"
15
- 3. Name: iona-ai (or your choice)
16
- 4. SDK: Docker
17
- 5. Upload all 4 files above
18
- 6. Space will auto-deploy in 2-3 minutes
19
-
20
- After Deployment:
21
- 1. Visit your space URL: https://huggingface.co/spaces/YOUR-USERNAME/iona-ai
22
- 2. Copy the External IP from dashboard
23
- 3. Add IP to MOFH API whitelist
24
- 4. Update PHP file line 33 with your HF Space URL
25
-
26
- Test Endpoints:
27
- - GET / - Dashboard
28
- - GET /health - Health check
29
- - GET /test - Test AI
30
- - POST /generate-website - Generate website
31
- - POST /create - Create MOFH account
32
-
33
- Status: PRODUCTION READY ✓
 
1
+ IONA AI - Hugging Face Deployment Instructions
2
+ ==============================================
3
+
4
+ READY TO DEPLOY! ✓
5
+
6
+ Files Needed:
7
+ - app.py (Main application)
8
+ - requirements.txt (Dependencies)
9
+ - Dockerfile (Container config)
10
+ - README.md (Documentation)
11
+
12
+ Quick Deploy to Hugging Face:
13
+ 1. Go to https://huggingface.co/spaces
14
+ 2. Click "Create new Space"
15
+ 3. Name: iona-ai (or your choice)
16
+ 4. SDK: Docker
17
+ 5. Upload all 4 files above
18
+ 6. Space will auto-deploy in 2-3 minutes
19
+
20
+ After Deployment:
21
+ 1. Visit your space URL: https://huggingface.co/spaces/YOUR-USERNAME/iona-ai
22
+ 2. Copy the External IP from dashboard
23
+ 3. Add IP to MOFH API whitelist
24
+ 4. Update PHP file line 33 with your HF Space URL
25
+
26
+ Test Endpoints:
27
+ - GET / - Dashboard
28
+ - GET /health - Health check
29
+ - GET /test - Test AI
30
+ - POST /generate-website - Generate website
31
+ - POST /create - Create MOFH account
32
+
33
+ Status: PRODUCTION READY ✓
DEPLOYMENT.md CHANGED
@@ -1,166 +1,166 @@
1
- # Hugging Face Space Deployment Guide
2
-
3
- ## Quick Start (5 minutes)
4
-
5
- ### Step 1: Create Hugging Face Account
6
- 1. Go to https://huggingface.co/join
7
- 2. Sign up (free)
8
- 3. Verify email
9
-
10
- ### Step 2: Create New Space
11
- 1. Go to https://huggingface.co/new-space
12
- 2. Fill in:
13
- - **Owner**: Your username
14
- - **Space name**: `mofh-api-proxy`
15
- - **License**: MIT
16
- - **Select SDK**: **Docker** (important!)
17
- - **Space hardware**: CPU basic - FREE
18
- - **Visibility**: Public (or Private if you have Pro)
19
- 3. Click **Create Space**
20
-
21
- ### Step 3: Upload Files
22
- You have 2 options:
23
-
24
- #### Option A: Git (Recommended)
25
- ```bash
26
- git clone https://huggingface.co/spaces/YOUR-USERNAME/mofh-api-proxy
27
- cd mofh-api-proxy
28
- ```
29
-
30
- Copy these files from `hf/` folder:
31
- - app.py
32
- - requirements.txt
33
- - Dockerfile
34
- - README.md
35
-
36
- ```bash
37
- git add .
38
- git commit -m "Initial commit"
39
- git push
40
- ```
41
-
42
- #### Option B: Web Upload
43
- 1. Click "Files" tab in your Space
44
- 2. Click "Add file" → "Upload files"
45
- 3. Upload: `app.py`, `requirements.txt`, `Dockerfile`, `README.md`
46
- 4. Click "Commit changes to main"
47
-
48
- ### Step 4: Set Environment Variables
49
- 1. Go to your Space settings (⚙️ icon)
50
- 2. Click "Variables and secrets"
51
- 3. Click "New secret"
52
- 4. Add:
53
-
54
- **Secret 1:**
55
- - Name: `MOFH_API_USERNAME`
56
- - Value: `rfK08b1cP89qBD2mG4WlN9bU4zrLP9bDMJiSyKWm5TiOO9BTNEbOgbOQ2Xyocf6A1z3fbCEVLbNQKh2mlbhFC4VWCyeUx4FF4EADbcRDiGTOLLiSVdzVrOSl8kjZIcVIVQATCPRyDxpme5S94XtaLHHyLQaVOy5TuWmenDo6aQI27SJXHSUFQy6dhJIZ2z8hWUXZPxEhgzCwD019gPuKDYWgb0hRm2lxPXCTTBn5alxpPszy1pz5RmmwqdmIDql`
57
-
58
- **Secret 2:**
59
- - Name: `MOFH_API_PASSWORD`
60
- - Value: `u6qymXFT9zJ3o1qv2lkphKZhgBN917xbKsnnpEgr2IUOtdOcHxlqaMakaGpaCdpUM5iwZrGE3cT9WgLZ3iGTxvRcwDZ3ut6nLv7dAPvSGFwd6gpjo5UxnaOF3FdSUGj2cMdxBd0NdM2fDKVab4gsASQerZk8JVt8c2LFfwtBYKCTrrxG8xwzzCsDP8fPA0ldlPzZkbKeBwSKu3HcscKeGlLVK1YMtYGjMG7wEAjXpqkjW8hsnFZURoSh4WpnINB`
61
-
62
- 5. Click "Save"
63
-
64
- ### Step 5: Wait for Build
65
- - Space will automatically build (2-3 minutes)
66
- - Status will show "Building" → "Running"
67
- - Once running, you'll see: **"App is running"**
68
-
69
- ### Step 6: Test Your API
70
- Your API URL: `https://YOUR-USERNAME-mofh-api-proxy.hf.space`
71
-
72
- Test in browser:
73
- ```
74
- https://YOUR-USERNAME-mofh-api-proxy.hf.space/
75
- ```
76
-
77
- Should return:
78
- ```json
79
- {
80
- "status": "online",
81
- "service": "MOFH API Proxy for Celestine Hosting",
82
- "endpoints": {...}
83
- }
84
- ```
85
-
86
- ### Step 7: Integrate with Your Site
87
-
88
- Copy `hf/hf-mofh-api.php` to your main site folder:
89
- ```bash
90
- copy hf\hf-mofh-api.php .
91
- ```
92
-
93
- Update `config.php`:
94
- ```php
95
- // Add this line
96
- define('HF_API_URL', 'https://YOUR-USERNAME-mofh-api-proxy.hf.space');
97
- ```
98
-
99
- Update `create-hosting.php` to use HF API:
100
- ```php
101
- require_once 'hf-mofh-api.php';
102
- $mofh = new HF_MOFH_API(HF_API_URL);
103
- $result = $mofh->createAccount($username, $password, $email, $domain);
104
- ```
105
-
106
- ## Testing
107
-
108
- ### Test 1: Connection Test
109
- ```bash
110
- curl https://YOUR-USERNAME-mofh-api-proxy.hf.space/
111
- ```
112
-
113
- ### Test 2: Create Account
114
- ```bash
115
- curl -X POST https://YOUR-USERNAME-mofh-api-proxy.hf.space/create-account \
116
- -H "Content-Type: application/json" \
117
- -d '{
118
- "username": "test123",
119
- "password": "TestPass123",
120
- "email": "test@example.com",
121
- "domain": "test123.yourdomain.com",
122
- "plan": "free"
123
- }'
124
- ```
125
-
126
- ## Troubleshooting
127
-
128
- ### Space shows "Building" forever
129
- - Check logs in Space
130
- - Make sure Dockerfile is correct
131
- - Verify all files uploaded
132
-
133
- ### "Application startup failed"
134
- - Check environment variables are set
135
- - Verify API credentials are correct
136
- - Check Space logs for errors
137
-
138
- ### API returns 500 error
139
- - Check MOFH API credentials
140
- - Verify MOFH server is accessible
141
- - Check Space logs
142
-
143
- ### Connection timeout from your site
144
- - Verify HF Space URL is correct
145
- - Check Space is running (not sleeping)
146
- - Test API directly in browser first
147
-
148
- ## Benefits
149
-
150
- ✅ **Free Forever** - Hugging Face Spaces are free
151
- ✅ **No Port Restrictions** - Bypasses ByetHost limitations
152
- ✅ **Always Online** - 99.9% uptime
153
- ✅ **Fast** - Global CDN
154
- ✅ **Secure** - HTTPS + encrypted secrets
155
- ✅ **Easy Updates** - Just push to git
156
-
157
- ## Cost
158
-
159
- **$0.00** - Completely free!
160
-
161
- ## Next Steps
162
-
163
- 1. Deploy Space (5 minutes)
164
- 2. Test API works
165
- 3. Integrate with your site
166
- 4. Create hosting accounts automatically! 🎉
 
1
+ # Hugging Face Space Deployment Guide
2
+
3
+ ## Quick Start (5 minutes)
4
+
5
+ ### Step 1: Create Hugging Face Account
6
+ 1. Go to https://huggingface.co/join
7
+ 2. Sign up (free)
8
+ 3. Verify email
9
+
10
+ ### Step 2: Create New Space
11
+ 1. Go to https://huggingface.co/new-space
12
+ 2. Fill in:
13
+ - **Owner**: Your username
14
+ - **Space name**: `mofh-api-proxy`
15
+ - **License**: MIT
16
+ - **Select SDK**: **Docker** (important!)
17
+ - **Space hardware**: CPU basic - FREE
18
+ - **Visibility**: Public (or Private if you have Pro)
19
+ 3. Click **Create Space**
20
+
21
+ ### Step 3: Upload Files
22
+ You have 2 options:
23
+
24
+ #### Option A: Git (Recommended)
25
+ ```bash
26
+ git clone https://huggingface.co/spaces/YOUR-USERNAME/mofh-api-proxy
27
+ cd mofh-api-proxy
28
+ ```
29
+
30
+ Copy these files from `hf/` folder:
31
+ - app.py
32
+ - requirements.txt
33
+ - Dockerfile
34
+ - README.md
35
+
36
+ ```bash
37
+ git add .
38
+ git commit -m "Initial commit"
39
+ git push
40
+ ```
41
+
42
+ #### Option B: Web Upload
43
+ 1. Click "Files" tab in your Space
44
+ 2. Click "Add file" → "Upload files"
45
+ 3. Upload: `app.py`, `requirements.txt`, `Dockerfile`, `README.md`
46
+ 4. Click "Commit changes to main"
47
+
48
+ ### Step 4: Set Environment Variables
49
+ 1. Go to your Space settings (⚙️ icon)
50
+ 2. Click "Variables and secrets"
51
+ 3. Click "New secret"
52
+ 4. Add:
53
+
54
+ **Secret 1:**
55
+ - Name: `MOFH_API_USERNAME`
56
+ - Value: `rfK08b1cP89qBD2mG4WlN9bU4zrLP9bDMJiSyKWm5TiOO9BTNEbOgbOQ2Xyocf6A1z3fbCEVLbNQKh2mlbhFC4VWCyeUx4FF4EADbcRDiGTOLLiSVdzVrOSl8kjZIcVIVQATCPRyDxpme5S94XtaLHHyLQaVOy5TuWmenDo6aQI27SJXHSUFQy6dhJIZ2z8hWUXZPxEhgzCwD019gPuKDYWgb0hRm2lxPXCTTBn5alxpPszy1pz5RmmwqdmIDql`
57
+
58
+ **Secret 2:**
59
+ - Name: `MOFH_API_PASSWORD`
60
+ - Value: `u6qymXFT9zJ3o1qv2lkphKZhgBN917xbKsnnpEgr2IUOtdOcHxlqaMakaGpaCdpUM5iwZrGE3cT9WgLZ3iGTxvRcwDZ3ut6nLv7dAPvSGFwd6gpjo5UxnaOF3FdSUGj2cMdxBd0NdM2fDKVab4gsASQerZk8JVt8c2LFfwtBYKCTrrxG8xwzzCsDP8fPA0ldlPzZkbKeBwSKu3HcscKeGlLVK1YMtYGjMG7wEAjXpqkjW8hsnFZURoSh4WpnINB`
61
+
62
+ 5. Click "Save"
63
+
64
+ ### Step 5: Wait for Build
65
+ - Space will automatically build (2-3 minutes)
66
+ - Status will show "Building" → "Running"
67
+ - Once running, you'll see: **"App is running"**
68
+
69
+ ### Step 6: Test Your API
70
+ Your API URL: `https://YOUR-USERNAME-mofh-api-proxy.hf.space`
71
+
72
+ Test in browser:
73
+ ```
74
+ https://YOUR-USERNAME-mofh-api-proxy.hf.space/
75
+ ```
76
+
77
+ Should return:
78
+ ```json
79
+ {
80
+ "status": "online",
81
+ "service": "MOFH API Proxy for Celestine Hosting",
82
+ "endpoints": {...}
83
+ }
84
+ ```
85
+
86
+ ### Step 7: Integrate with Your Site
87
+
88
+ Copy `hf/hf-mofh-api.php` to your main site folder:
89
+ ```bash
90
+ copy hf\hf-mofh-api.php .
91
+ ```
92
+
93
+ Update `config.php`:
94
+ ```php
95
+ // Add this line
96
+ define('HF_API_URL', 'https://YOUR-USERNAME-mofh-api-proxy.hf.space');
97
+ ```
98
+
99
+ Update `create-hosting.php` to use HF API:
100
+ ```php
101
+ require_once 'hf-mofh-api.php';
102
+ $mofh = new HF_MOFH_API(HF_API_URL);
103
+ $result = $mofh->createAccount($username, $password, $email, $domain);
104
+ ```
105
+
106
+ ## Testing
107
+
108
+ ### Test 1: Connection Test
109
+ ```bash
110
+ curl https://YOUR-USERNAME-mofh-api-proxy.hf.space/
111
+ ```
112
+
113
+ ### Test 2: Create Account
114
+ ```bash
115
+ curl -X POST https://YOUR-USERNAME-mofh-api-proxy.hf.space/create-account \
116
+ -H "Content-Type: application/json" \
117
+ -d '{
118
+ "username": "test123",
119
+ "password": "TestPass123",
120
+ "email": "test@example.com",
121
+ "domain": "test123.yourdomain.com",
122
+ "plan": "free"
123
+ }'
124
+ ```
125
+
126
+ ## Troubleshooting
127
+
128
+ ### Space shows "Building" forever
129
+ - Check logs in Space
130
+ - Make sure Dockerfile is correct
131
+ - Verify all files uploaded
132
+
133
+ ### "Application startup failed"
134
+ - Check environment variables are set
135
+ - Verify API credentials are correct
136
+ - Check Space logs for errors
137
+
138
+ ### API returns 500 error
139
+ - Check MOFH API credentials
140
+ - Verify MOFH server is accessible
141
+ - Check Space logs
142
+
143
+ ### Connection timeout from your site
144
+ - Verify HF Space URL is correct
145
+ - Check Space is running (not sleeping)
146
+ - Test API directly in browser first
147
+
148
+ ## Benefits
149
+
150
+ ✅ **Free Forever** - Hugging Face Spaces are free
151
+ ✅ **No Port Restrictions** - Bypasses ByetHost limitations
152
+ ✅ **Always Online** - 99.9% uptime
153
+ ✅ **Fast** - Global CDN
154
+ ✅ **Secure** - HTTPS + encrypted secrets
155
+ ✅ **Easy Updates** - Just push to git
156
+
157
+ ## Cost
158
+
159
+ **$0.00** - Completely free!
160
+
161
+ ## Next Steps
162
+
163
+ 1. Deploy Space (5 minutes)
164
+ 2. Test API works
165
+ 3. Integrate with your site
166
+ 4. Create hosting accounts automatically! 🎉
Dockerfile CHANGED
@@ -1,11 +1,11 @@
1
- FROM tiangolo/uvicorn-gunicorn-fastapi:python3.11-slim
2
-
3
- COPY requirements.txt /app/
4
- RUN pip install --no-cache-dir -r requirements.txt
5
-
6
- COPY app.py /app/
7
-
8
- ENV PORT=7860
9
- EXPOSE 7860
10
-
11
  CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
 
1
+ FROM tiangolo/uvicorn-gunicorn-fastapi:python3.11-slim
2
+
3
+ COPY requirements.txt /app/
4
+ RUN pip install --no-cache-dir -r requirements.txt
5
+
6
+ COPY app.py /app/
7
+
8
+ ENV PORT=7860
9
+ EXPOSE 7860
10
+
11
  CMD ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "7860"]
GITHUB_DEPLOYMENT_GUIDE.md ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚀 GitHub Deployment System - Complete Guide
2
+
3
+ ## Overview
4
+
5
+ The Celestine Hosting GitHub Deployment System enables automatic CI/CD deployments from GitHub repositories to VistaPanel hosting using GitHub Actions. This guide covers setup, configuration, and usage.
6
+
7
+ ---
8
+
9
+ ## 🏗️ Architecture
10
+
11
+ ```
12
+ ┌─────────────────────────────────────────────────────────────────────┐
13
+ │ USER GITHUB REPOSITORY │
14
+ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │
15
+ │ │ React App │ │ .github/ │ │ Source │ │
16
+ │ │ (Source) │ │ workflows/ │ │ Code │ │
17
+ │ └──────────────┘ └──────────────┘ └──────────────┘ │
18
+ │ │ │ │ │
19
+ │ └─────────────────┴─────────────────┘ │
20
+ │ │ │
21
+ │ ▼ │
22
+ │ ┌─────────────────┐ │
23
+ │ │ GitHub Actions │ │
24
+ │ │ (Build Worker) │ │
25
+ │ └─────────────────┘ │
26
+ │ │ │
27
+ │ ▼ │
28
+ │ ┌──────────────────────────────┐ │
29
+ │ │ FastAPI (HF Space) │ │
30
+ │ │ - GitHub App Integration │ │
31
+ │ │ - Secret Management │ │
32
+ │ │ - Workflow Injection │ │
33
+ │ │ - Deployment Tracking │ │
34
+ │ └──────────────────────────────┘ │
35
+ │ │ │
36
+ │ ▼ │
37
+ │ ┌─────────────────┐ │
38
+ │ │ VistaPanel │ │
39
+ │ │ (FTP Storage) │ │
40
+ │ └─────────────────┘ │
41
+ └─────────────────────────────────────────────────────────────────────┘
42
+ ```
43
+
44
+ ---
45
+
46
+ ## 📋 Prerequisites
47
+
48
+ ### 1. GitHub App Setup
49
+
50
+ Create a GitHub App to act on behalf of users:
51
+
52
+ 1. Go to **GitHub Settings > Developer Settings > GitHub Apps > New GitHub App**
53
+
54
+ 2. **Basic Information:**
55
+ - GitHub App name: `Celestine Hosting`
56
+ - Homepage URL: `https://celestine.indevs.in`
57
+ - Callback URL: `https://celestine.indevs.in/github-deploy`
58
+ - Setup URL: (leave blank)
59
+ - Webhook: Uncheck "Active"
60
+
61
+ 3. **Permissions:**
62
+ - Repository permissions:
63
+ - Contents: **Read & Write** (To inject workflow files)
64
+ - Actions: **Read & Write** (To trigger builds)
65
+ - Secrets: **Read & Write** (To store FTP credentials)
66
+ - Metadata: **Read-only** (Required)
67
+ - Account permissions: None needed
68
+
69
+ 4. **Where can this GitHub App be installed?**
70
+ - Select "Any account"
71
+
72
+ 5. **Save and Generate:**
73
+ - Save the App ID
74
+ - Save the Client ID
75
+ - Save the Client Secret
76
+ - Generate and download Private Key (PEM file)
77
+
78
+ ### 2. Environment Variables
79
+
80
+ Add these to your Hugging Face Space:
81
+
82
+ ```bash
83
+ # GitHub App Configuration
84
+ GITHUB_APP_ID=123456
85
+ GITHUB_CLIENT_ID=Iv1.abc123def456
86
+ GITHUB_CLIENT_SECRET=your_client_secret_here
87
+ GITHUB_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----
88
+ MIIEpAIBAAKCAQEA...
89
+ ...
90
+ -----END RSA PRIVATE KEY-----"
91
+ ```
92
+
93
+ **Important:** For `GITHUB_PRIVATE_KEY`, replace actual newlines with `\n`:
94
+ ```bash
95
+ GITHUB_PRIVATE_KEY="-----BEGIN RSA PRIVATE KEY-----\nMIIEpAIBAAKCAQEA...\n...\n-----END RSA PRIVATE KEY-----"
96
+ ```
97
+
98
+ ### 3. Update Frontend Configuration
99
+
100
+ In `htdocs/github-deploy.php`, update the GitHub Client ID:
101
+
102
+ ```javascript
103
+ const GITHUB_CLIENT_ID = 'Iv1.abc123def456'; // Your actual Client ID
104
+ ```
105
+
106
+ ---
107
+
108
+ ## 🎯 Supported Project Types
109
+
110
+ The system automatically detects and configures deployments for:
111
+
112
+ ### Frontend Frameworks
113
+
114
+ | Framework | Detection | Build Command | Output Dir |
115
+ |-----------|-----------|---------------|------------|
116
+ | **React** | `react` in dependencies | `npm run build` | `build` |
117
+ | **Vue** | `vue` in dependencies | `npm run build` | `dist` |
118
+ | **Angular** | `@angular/core` in dependencies | `npm run build -- --configuration production` | `dist` |
119
+ | **Next.js** | `next` in dependencies | `npm run build && npm run export` | `out` |
120
+ | **Nuxt** | `nuxt` in dependencies | `npm run generate` | `dist` |
121
+ | **Svelte** | `svelte` in dependencies | `npm run build` | `public` |
122
+ | **Vite** | `vite` in devDependencies | `npm run build` | `dist` |
123
+ | **Static HTML** | `index.html` present | (none) | `.` |
124
+
125
+ ### Custom Configuration
126
+
127
+ For projects with custom build setups, the system reads `package.json` scripts:
128
+ - Uses `build` script if available
129
+ - Falls back to framework defaults
130
+ - Supports custom output directories
131
+
132
+ ---
133
+
134
+ ## 🔧 How It Works
135
+
136
+ ### 1. User Connects GitHub
137
+
138
+ ```javascript
139
+ // User clicks "Connect with GitHub"
140
+ // Redirects to GitHub OAuth
141
+ https://github.com/login/oauth/authorize?
142
+ client_id=YOUR_CLIENT_ID&
143
+ redirect_uri=https://celestine.indevs.in/github-deploy&
144
+ scope=repo,workflow
145
+ ```
146
+
147
+ ### 2. OAuth Code Exchange
148
+
149
+ ```javascript
150
+ // Backend exchanges code for access token
151
+ POST /github/oauth/exchange
152
+ {
153
+ "code": "oauth_code_from_github"
154
+ }
155
+
156
+ // Response
157
+ {
158
+ "success": true,
159
+ "access_token": "gho_...",
160
+ "token_type": "bearer",
161
+ "scope": "repo,workflow"
162
+ }
163
+ ```
164
+
165
+ ### 3. Repository Detection
166
+
167
+ ```javascript
168
+ // Get user's repositories
169
+ POST /github/repos
170
+ {
171
+ "access_token": "gho_..."
172
+ }
173
+
174
+ // Response
175
+ {
176
+ "success": true,
177
+ "repositories": [...],
178
+ "count": 25
179
+ }
180
+ ```
181
+
182
+ ### 4. Project Type Detection
183
+
184
+ ```javascript
185
+ // Detect project type and build configuration
186
+ POST /github/detect-project
187
+ {
188
+ "owner": "username",
189
+ "repo": "my-react-app",
190
+ "access_token": "gho_..."
191
+ }
192
+
193
+ // Response
194
+ {
195
+ "success": true,
196
+ "project_config": {
197
+ "type": "react",
198
+ "build_command": "npm run build",
199
+ "output_dir": "build",
200
+ "install_command": "npm ci"
201
+ }
202
+ }
203
+ ```
204
+
205
+ ### 5. Deployment Setup
206
+
207
+ ```javascript
208
+ // Complete deployment setup
209
+ POST /github/setup-deployment
210
+ {
211
+ "owner": "username",
212
+ "repo": "my-react-app",
213
+ "access_token": "gho_...",
214
+ "ftp_server": "ftp.celestine.indevs.in",
215
+ "ftp_username": "celestine_12345",
216
+ "ftp_password": "secure_password",
217
+ "branch": "main"
218
+ }
219
+
220
+ // Response
221
+ {
222
+ "success": true,
223
+ "project_type": "react",
224
+ "build_command": "npm run build",
225
+ "output_dir": "build",
226
+ "workflow_url": "https://github.com/username/my-react-app/blob/main/.github/workflows/celestine_deploy.yml",
227
+ "actions_url": "https://github.com/username/my-react-app/actions"
228
+ }
229
+ ```
230
+
231
+ **What happens:**
232
+ 1. ✅ Detects project type (React, Vue, etc.)
233
+ 2. ✅ Creates GitHub Secrets (`FTP_USERNAME`, `FTP_PASSWORD`)
234
+ 3. ✅ Generates workflow YAML file
235
+ 4. ✅ Commits workflow to `.github/workflows/celestine_deploy.yml`
236
+
237
+ ### 6. Automatic Deployment
238
+
239
+ Once setup is complete, every push to the configured branch triggers:
240
+
241
+ ```yaml
242
+ # .github/workflows/celestine_deploy.yml
243
+ name: Deploy to Celestine Hosting
244
+
245
+ on:
246
+ push:
247
+ branches: [ main ]
248
+ workflow_dispatch:
249
+
250
+ jobs:
251
+ deploy:
252
+ runs-on: ubuntu-latest
253
+
254
+ steps:
255
+ - name: 📥 Checkout code
256
+ uses: actions/checkout@v4
257
+
258
+ - name: 📦 Setup Node.js
259
+ uses: actions/setup-node@v4
260
+ with:
261
+ node-version: '18'
262
+ cache: 'npm'
263
+
264
+ - name: 📚 Install dependencies
265
+ run: npm ci
266
+
267
+ - name: 🔨 Build project
268
+ run: npm run build
269
+ env:
270
+ CI: false
271
+
272
+ - name: 🚀 Deploy to VistaPanel via FTP
273
+ uses: SamKirkland/FTP-Deploy-Action@v4.3.4
274
+ with:
275
+ server: ftp.celestine.indevs.in
276
+ username: ${{ secrets.FTP_USERNAME }}
277
+ password: ${{ secrets.FTP_PASSWORD }}
278
+ local-dir: ./build/
279
+ server-dir: ./htdocs/
280
+ dangerous-clean-slate: false
281
+ exclude: |
282
+ **/.git*
283
+ **/.git*/**
284
+ **/node_modules/**
285
+ **/.env
286
+
287
+ - name: ✅ Deployment complete
288
+ run: |
289
+ echo "🎉 Deployment successful!"
290
+ echo "🌐 Your site is live at: https://celestine_12345.celestine.indevs.in"
291
+ ```
292
+
293
+ ---
294
+
295
+ ## 📊 Deployment Tracking
296
+
297
+ ### Get Workflow Runs
298
+
299
+ ```javascript
300
+ POST /github/workflow-runs
301
+ {
302
+ "owner": "username",
303
+ "repo": "my-react-app",
304
+ "access_token": "gho_...",
305
+ "limit": 10
306
+ }
307
+
308
+ // Response
309
+ {
310
+ "success": true,
311
+ "runs": [
312
+ {
313
+ "id": 123456789,
314
+ "name": "Deploy to Celestine Hosting",
315
+ "status": "completed",
316
+ "conclusion": "success",
317
+ "created_at": "2026-05-04T10:30:00Z",
318
+ "updated_at": "2026-05-04T10:35:00Z",
319
+ "html_url": "https://github.com/username/my-react-app/actions/runs/123456789",
320
+ "run_number": 42
321
+ }
322
+ ],
323
+ "count": 10
324
+ }
325
+ ```
326
+
327
+ ### Get Workflow Logs
328
+
329
+ ```javascript
330
+ POST /github/workflow-logs
331
+ {
332
+ "owner": "username",
333
+ "repo": "my-react-app",
334
+ "run_id": 123456789,
335
+ "access_token": "gho_..."
336
+ }
337
+
338
+ // Response
339
+ {
340
+ "success": true,
341
+ "logs": "2026-05-04T10:30:00.000Z Checkout code\n..."
342
+ }
343
+ ```
344
+
345
+ ### Trigger Manual Deployment
346
+
347
+ ```javascript
348
+ POST /github/trigger-workflow
349
+ {
350
+ "owner": "username",
351
+ "repo": "my-react-app",
352
+ "access_token": "gho_...",
353
+ "workflow_file": "celestine_deploy.yml",
354
+ "branch": "main"
355
+ }
356
+
357
+ // Response
358
+ {
359
+ "success": true,
360
+ "message": "Workflow triggered successfully"
361
+ }
362
+ ```
363
+
364
+ ---
365
+
366
+ ## 🎨 Frontend Features
367
+
368
+ ### Terminal-Style Logs
369
+
370
+ The frontend displays deployment logs in a terminal-like interface:
371
+
372
+ ```
373
+ [10:30:15] ℹ Setting up deployment for username/my-react-app...
374
+ [10:30:16] ℹ Branch: main
375
+ [10:30:16] ℹ FTP Server: ftp.celestine.indevs.in
376
+ [10:30:17] ℹ Detecting project type...
377
+ [10:30:18] ✓ Detected: react
378
+ [10:30:19] ℹ Creating FTP secrets...
379
+ [10:30:21] ✓ Secrets created successfully
380
+ [10:30:22] ℹ Generating workflow file...
381
+ [10:30:23] ℹ Injecting workflow into repository...
382
+ [10:30:25] ✓ Workflow injected successfully
383
+ [10:30:25] ✓ Deployment configured successfully!
384
+ [10:30:25] ℹ View workflow: https://github.com/username/my-react-app/blob/main/.github/workflows/celestine_deploy.yml
385
+ [10:30:25] ℹ Monitor deployments: https://github.com/username/my-react-app/actions
386
+ ```
387
+
388
+ ### Color-Coded Messages
389
+
390
+ - 🔵 **Info** (Blue): General information
391
+ - 🟢 **Success** (Green): Successful operations
392
+ - 🟡 **Warning** (Yellow): Warnings
393
+ - 🔴 **Error** (Red): Errors
394
+
395
+ ---
396
+
397
+ ## 🔐 Security
398
+
399
+ ### Secret Encryption
400
+
401
+ FTP credentials are encrypted using GitHub's public key before storage:
402
+
403
+ ```python
404
+ def encrypt_secret(public_key: str, secret_value: str) -> str:
405
+ """Encrypt a secret using the repository's public key"""
406
+ public_key_obj = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder)
407
+ sealed_box = public.SealedBox(public_key_obj)
408
+ encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
409
+ return base64.b64encode(encrypted).decode("utf-8")
410
+ ```
411
+
412
+ ### Access Token Storage
413
+
414
+ - Access tokens are stored in browser's `localStorage`
415
+ - Tokens are never logged or exposed
416
+ - Tokens are used only for API calls to GitHub
417
+
418
+ ### Best Practices
419
+
420
+ 1. **Never commit secrets** to your repository
421
+ 2. **Use GitHub Secrets** for sensitive data
422
+ 3. **Rotate FTP passwords** regularly
423
+ 4. **Review workflow files** before committing
424
+ 5. **Monitor deployment logs** for suspicious activity
425
+
426
+ ---
427
+
428
+ ## 🐛 Troubleshooting
429
+
430
+ ### Common Issues
431
+
432
+ #### 1. "GitHub integration not configured"
433
+
434
+ **Cause:** Missing environment variables
435
+
436
+ **Solution:**
437
+ ```bash
438
+ # Check Hugging Face Space settings
439
+ # Ensure all GitHub environment variables are set:
440
+ GITHUB_APP_ID
441
+ GITHUB_CLIENT_ID
442
+ GITHUB_CLIENT_SECRET
443
+ GITHUB_PRIVATE_KEY
444
+ ```
445
+
446
+ #### 2. "Failed to create FTP secrets"
447
+
448
+ **Cause:** Insufficient GitHub App permissions
449
+
450
+ **Solution:**
451
+ - Go to GitHub App settings
452
+ - Ensure "Secrets: Read & Write" permission is enabled
453
+ - Reinstall the app on the repository
454
+
455
+ #### 3. "Workflow injection failed"
456
+
457
+ **Cause:** Missing "Contents: Write" permission
458
+
459
+ **Solution:**
460
+ - Check GitHub App permissions
461
+ - Ensure "Contents: Read & Write" is enabled
462
+ - Verify the repository is not archived
463
+
464
+ #### 4. "Build failed: Command not found"
465
+
466
+ **Cause:** Missing build script in `package.json`
467
+
468
+ **Solution:**
469
+ ```json
470
+ {
471
+ "scripts": {
472
+ "build": "react-scripts build"
473
+ }
474
+ }
475
+ ```
476
+
477
+ #### 5. "FTP deployment failed"
478
+
479
+ **Cause:** Incorrect FTP credentials or server
480
+
481
+ **Solution:**
482
+ - Verify FTP credentials in VistaPanel
483
+ - Check FTP server address: `ftp.celestine.indevs.in`
484
+ - Ensure hosting account is active
485
+
486
+ ---
487
+
488
+ ## 📚 API Reference
489
+
490
+ ### Complete Endpoint List
491
+
492
+ | Method | Endpoint | Description |
493
+ |--------|----------|-------------|
494
+ | GET | `/github/status` | Check GitHub integration status |
495
+ | POST | `/github/oauth/exchange` | Exchange OAuth code for token |
496
+ | POST | `/github/repos` | Get user's repositories |
497
+ | POST | `/github/detect-project` | Detect project type |
498
+ | POST | `/github/setup-deployment` | Complete deployment setup |
499
+ | POST | `/github/workflow-runs` | Get workflow run history |
500
+ | POST | `/github/workflow-logs` | Get workflow run logs |
501
+ | POST | `/github/trigger-workflow` | Manually trigger workflow |
502
+
503
+ ### Request/Response Examples
504
+
505
+ See the "How It Works" section above for detailed examples.
506
+
507
+ ---
508
+
509
+ ## 🚀 Deployment Flow Summary
510
+
511
+ 1. **User connects GitHub account** → OAuth flow
512
+ 2. **User selects repository** → Repository list displayed
513
+ 3. **System detects project type** → Automatic detection
514
+ 4. **User selects hosting account** → FTP credentials retrieved
515
+ 5. **System creates secrets** → Encrypted and stored in GitHub
516
+ 6. **System injects workflow** → Committed to repository
517
+ 7. **User pushes code** → GitHub Actions triggered
518
+ 8. **Build and deploy** → Automatic deployment to VistaPanel
519
+ 9. **Site is live** → Accessible via subdomain
520
+
521
+ ---
522
+
523
+ ## 📝 Notes
524
+
525
+ - **Build Time:** Most React/Vue builds complete in 2-5 minutes
526
+ - **FTP Speed:** VistaPanel FTP is optimized for small to medium sites
527
+ - **Node.js:** VistaPanel cannot run Node.js servers (static sites only)
528
+ - **Security:** All secrets are encrypted and never exposed in logs
529
+ - **Monitoring:** View deployment status in GitHub Actions tab
530
+
531
+ ---
532
+
533
+ ## 🎉 Success!
534
+
535
+ Your GitHub repository is now connected to Celestine Hosting with automatic CI/CD deployments!
536
+
537
+ Every push to your configured branch will automatically:
538
+ 1. ✅ Build your project
539
+ 2. ✅ Deploy to VistaPanel
540
+ 3. ✅ Make your site live
541
+
542
+ **Happy deploying! 🚀**
IMPROVEMENTS.md CHANGED
@@ -1,376 +1,376 @@
1
- # HF Space app.py - ENHANCED VERSION ✅
2
-
3
- ## 🎉 ALL IMPROVEMENTS APPLIED
4
-
5
- ### **✨ NEW FEATURES**
6
-
7
- #### 1. **Beautiful Uptime Dashboard** 🎨
8
- - Full HTML dashboard at root URL (`/`)
9
- - Real-time system statistics
10
- - External IP display (for MOFH whitelist)
11
- - Auto-refresh every 30 seconds
12
- - Animated UI with gradient background
13
- - Progress bars for CPU/Memory usage
14
-
15
- #### 2. **Request Tracking** 📊
16
- - Total requests counter
17
- - Generation requests counter
18
- - Account creation counter
19
- - Error counter
20
- - API key usage tracking (round-robin)
21
-
22
- #### 3. **Health Check Endpoint** 🏥
23
- - `GET /health` - JSON health status
24
- - Uptime in seconds
25
- - Timestamp
26
- - Request statistics
27
- - Perfect for monitoring tools
28
-
29
- #### 4. **Test Endpoint** 🧪
30
- - `GET /test` - Test AI generation
31
- - Simple "Hello World" test
32
- - Verifies Groq API connectivity
33
- - Returns success/failure status
34
- - Shows token usage
35
-
36
- #### 5. **Input Validation** ✅
37
- - Prompt validation (10-10000 chars)
38
- - Username validation (3-20 chars)
39
- - Email format validation
40
- - Automatic trimming of whitespace
41
- - Pydantic validators
42
-
43
- ---
44
-
45
- ## 🐛 BUGS FIXED
46
-
47
- ### **Critical Fixes:**
48
-
49
- 1. ✅ **Missing psutil import** - Added for system stats
50
- 2. ✅ **No request tracking** - Added global counters
51
- 3. ✅ **No input validation** - Added Pydantic validators
52
- 4. ✅ **No health check** - Added `/health` endpoint
53
- 5. ✅ **No test endpoint** - Added `/test` endpoint
54
- 6. ✅ **Logging not configured** - Added proper logging setup
55
- 7. ✅ **No error counting** - Track errors in REQUEST_COUNT
56
- 8. ✅ **No uptime tracking** - Added START_TIME global
57
- 9. ✅ **Plain JSON response** - Beautiful HTML dashboard
58
- 10. ✅ **No external IP display** - Prominent display in UI
59
-
60
- ---
61
-
62
- ## 📋 NEW ENDPOINTS
63
-
64
- ### **1. GET /** (Dashboard)
65
- **Response**: Beautiful HTML dashboard with:
66
- - System uptime
67
- - External IP (for MOFH whitelist)
68
- - CPU & Memory usage
69
- - Request statistics
70
- - API key usage
71
- - Available endpoints
72
- - Developer info
73
- - Auto-refresh
74
-
75
- ### **2. GET /health**
76
- **Response**: JSON
77
- ```json
78
- {
79
- "status": "healthy",
80
- "uptime_seconds": 12345,
81
- "timestamp": "2026-01-15T10:30:00",
82
- "requests": {
83
- "total": 150,
84
- "generate": 100,
85
- "create": 45,
86
- "errors": 5
87
- }
88
- }
89
- ```
90
-
91
- ### **3. GET /test**
92
- **Response**: JSON
93
- ```json
94
- {
95
- "success": true,
96
- "model": "llama-3.3-70b-versatile",
97
- "response_length": 234,
98
- "tokens_used": {"prompt_tokens": 50, "completion_tokens": 100},
99
- "message": "AI is working correctly!"
100
- }
101
- ```
102
-
103
- ### **4. POST /generate-website** (Enhanced)
104
- - Now tracks requests
105
- - Validates input (10-10000 chars)
106
- - Counts errors
107
- - Same response format
108
-
109
- ### **5. POST /create** (Enhanced)
110
- - Now tracks requests
111
- - Validates username (3-20 chars)
112
- - Validates email format
113
- - Counts errors
114
- - Same response format
115
-
116
- ---
117
-
118
- ## 🎨 DASHBOARD FEATURES
119
-
120
- ### **Visual Design:**
121
- - Gradient purple background
122
- - Glassmorphism cards
123
- - Smooth animations
124
- - Hover effects
125
- - Progress bars
126
- - Responsive grid layout
127
- - Auto-refresh (30s)
128
-
129
- ### **Information Displayed:**
130
-
131
- **Uptime Card:**
132
- - Running since timestamp
133
- - Uptime (hours, minutes, seconds)
134
- - Total requests
135
- - Error count
136
-
137
- **Network Info Card:**
138
- - Hostname
139
- - Local IP
140
- - **External IP (highlighted)**
141
- - Warning to add IP to MOFH whitelist
142
-
143
- **System Resources Card:**
144
- - CPU usage (%)
145
- - Memory usage (%)
146
- - Memory used/total (GB)
147
- - Visual progress bars
148
-
149
- **AI Configuration Card:**
150
- - Active models count
151
- - API keys count
152
- - Generation count
153
- - API key usage breakdown
154
-
155
- **API Endpoints Card:**
156
- - All available endpoints
157
- - HTTP methods
158
- - Descriptions
159
-
160
- **Developer Info Card:**
161
- - Developer name
162
- - GitHub link
163
- - Portfolio link
164
- - Version number
165
-
166
- ---
167
-
168
- ## 🔧 CONFIGURATION
169
-
170
- ### **Dependencies (requirements.txt):**
171
- ```
172
- fastapi==0.104.1
173
- uvicorn[standard]==0.24.0
174
- pydantic==2.5.0
175
- requests==2.31.0
176
- psutil==5.9.6
177
- python-multipart==0.0.6
178
- ```
179
-
180
- ### **Install:**
181
- ```bash
182
- pip install -r requirements.txt
183
- ```
184
-
185
- ### **Run:**
186
- ```bash
187
- uvicorn app:app --host 0.0.0.0 --port 7860
188
- ```
189
-
190
- ---
191
-
192
- ## 🧪 TESTING
193
-
194
- ### **1. Test Dashboard:**
195
- ```
196
- http://your-space.hf.space/
197
- ```
198
- Expected: Beautiful dashboard with all stats
199
-
200
- ### **2. Test Health Check:**
201
- ```
202
- http://your-space.hf.space/health
203
- ```
204
- Expected: JSON with status "healthy"
205
-
206
- ### **3. Test AI:**
207
- ```
208
- http://your-space.hf.space/test
209
- ```
210
- Expected: JSON with success=true
211
-
212
- ### **4. Test Generation:**
213
- ```bash
214
- curl -X POST http://your-space.hf.space/generate-website \
215
- -H "Content-Type: application/json" \
216
- -d '{
217
- "prompt": "Create a simple portfolio website",
218
- "business_type": "portfolio",
219
- "color_scheme": "modern"
220
- }'
221
- ```
222
- Expected: JSON with success=true and files
223
-
224
- ### **5. Test Validation:**
225
- ```bash
226
- curl -X POST http://your-space.hf.space/generate-website \
227
- -H "Content-Type: application/json" \
228
- -d '{"prompt": "short"}'
229
- ```
230
- Expected: 422 error (validation failed)
231
-
232
- ---
233
-
234
- ## 📊 MONITORING
235
-
236
- ### **Check System Status:**
237
- 1. Open dashboard in browser
238
- 2. Check external IP
239
- 3. Verify uptime
240
- 4. Monitor CPU/Memory
241
- 5. Check request counts
242
- 6. Review error count
243
-
244
- ### **Health Monitoring:**
245
- - Use `/health` endpoint
246
- - Monitor uptime_seconds
247
- - Track request counts
248
- - Alert on high error count
249
-
250
- ### **AI Testing:**
251
- - Use `/test` endpoint regularly
252
- - Verify success=true
253
- - Check response times
254
- - Monitor token usage
255
-
256
- ---
257
-
258
- ## 🚀 DEPLOYMENT CHECKLIST
259
-
260
- ### **Before Deploying:**
261
- - [ ] Update Groq API keys (if needed)
262
- - [ ] Verify MOFH credentials
263
- - [ ] Install dependencies
264
- - [ ] Test locally first
265
-
266
- ### **After Deploying:**
267
- - [ ] Visit dashboard
268
- - [ ] Copy external IP
269
- - [ ] Add IP to MOFH whitelist
270
- - [ ] Test `/health` endpoint
271
- - [ ] Test `/test` endpoint
272
- - [ ] Test website generation
273
- - [ ] Monitor for errors
274
-
275
- ---
276
-
277
- ## 💡 USAGE TIPS
278
-
279
- ### **1. External IP for MOFH:**
280
- - Dashboard shows external IP prominently
281
- - Copy this IP
282
- - Add to MOFH API whitelist
283
- - Required for account creation
284
-
285
- ### **2. Monitoring:**
286
- - Dashboard auto-refreshes every 30s
287
- - Check regularly for errors
288
- - Monitor CPU/Memory usage
289
- - Track request patterns
290
-
291
- ### **3. Testing:**
292
- - Use `/test` before production
293
- - Verify AI is responding
294
- - Check token usage
295
- - Ensure no errors
296
-
297
- ### **4. Debugging:**
298
- - Check error count on dashboard
299
- - Review logs for details
300
- - Test with `/test` endpoint
301
- - Verify API keys are valid
302
-
303
- ---
304
-
305
- ## 🎯 WHAT'S IMPROVED
306
-
307
- ### **Before:**
308
- - Plain JSON response
309
- - No uptime tracking
310
- - No request counting
311
- - No input validation
312
- - No health check
313
- - No test endpoint
314
- - No external IP display
315
- - No system monitoring
316
-
317
- ### **After:**
318
- - ✅ Beautiful HTML dashboard
319
- - ✅ Uptime tracking with display
320
- - ✅ Request counting (total, generate, create, errors)
321
- - ✅ Input validation (prompt, username, email)
322
- - ✅ Health check endpoint
323
- - Test endpoint for AI
324
- - ✅ External IP prominently displayed
325
- - ✅ System monitoring (CPU, Memory)
326
- - ✅ API key usage tracking
327
- - ✅ Auto-refresh dashboard
328
- - ✅ Responsive design
329
- - ✅ Error tracking
330
-
331
- ---
332
-
333
- ## 📝 NOTES
334
-
335
- ### **External IP:**
336
- - Displayed prominently on dashboard
337
- - Required for MOFH API access
338
- - Add to MOFH whitelist
339
- - Changes if server restarts
340
-
341
- ### **Request Tracking:**
342
- - Resets on server restart
343
- - Tracks all requests
344
- - Separates by type
345
- - Counts errors
346
-
347
- ### **System Stats:**
348
- - Real-time CPU usage
349
- - Real-time memory usage
350
- - Updates on refresh
351
- - Requires psutil
352
-
353
- ### **Auto-Refresh:**
354
- - Dashboard refreshes every 30s
355
- - Keeps stats current
356
- - Can be disabled if needed
357
- - Smooth animations
358
-
359
- ---
360
-
361
- ## ✨ FINAL STATUS
362
-
363
- **System Status**: ✅ PRODUCTION READY
364
-
365
- **Features Added**: 10+
366
- **Bugs Fixed**: 10+
367
- **New Endpoints**: 3
368
- **UI Improvements**: Complete redesign
369
-
370
- **Ready to deploy to Hugging Face Space!** 🚀
371
-
372
- ---
373
-
374
- **Developer**: Pratyush Srivastava
375
- **Version**: 2026.1.0 (Enhanced)
376
- **Status**: ✅ ALL IMPROVEMENTS APPLIED
 
1
+ # HF Space app.py - ENHANCED VERSION ✅
2
+
3
+ ## 🎉 ALL IMPROVEMENTS APPLIED
4
+
5
+ ### **✨ NEW FEATURES**
6
+
7
+ #### 1. **Beautiful Uptime Dashboard** 🎨
8
+ - Full HTML dashboard at root URL (`/`)
9
+ - Real-time system statistics
10
+ - External IP display (for MOFH whitelist)
11
+ - Auto-refresh every 30 seconds
12
+ - Animated UI with gradient background
13
+ - Progress bars for CPU/Memory usage
14
+
15
+ #### 2. **Request Tracking** 📊
16
+ - Total requests counter
17
+ - Generation requests counter
18
+ - Account creation counter
19
+ - Error counter
20
+ - API key usage tracking (round-robin)
21
+
22
+ #### 3. **Health Check Endpoint** 🏥
23
+ - `GET /health` - JSON health status
24
+ - Uptime in seconds
25
+ - Timestamp
26
+ - Request statistics
27
+ - Perfect for monitoring tools
28
+
29
+ #### 4. **Test Endpoint** 🧪
30
+ - `GET /test` - Test AI generation
31
+ - Simple "Hello World" test
32
+ - Verifies Groq API connectivity
33
+ - Returns success/failure status
34
+ - Shows token usage
35
+
36
+ #### 5. **Input Validation** ✅
37
+ - Prompt validation (10-10000 chars)
38
+ - Username validation (3-20 chars)
39
+ - Email format validation
40
+ - Automatic trimming of whitespace
41
+ - Pydantic validators
42
+
43
+ ---
44
+
45
+ ## 🐛 BUGS FIXED
46
+
47
+ ### **Critical Fixes:**
48
+
49
+ 1. ✅ **Missing psutil import** - Added for system stats
50
+ 2. ✅ **No request tracking** - Added global counters
51
+ 3. ✅ **No input validation** - Added Pydantic validators
52
+ 4. ✅ **No health check** - Added `/health` endpoint
53
+ 5. ✅ **No test endpoint** - Added `/test` endpoint
54
+ 6. ✅ **Logging not configured** - Added proper logging setup
55
+ 7. ✅ **No error counting** - Track errors in REQUEST_COUNT
56
+ 8. ✅ **No uptime tracking** - Added START_TIME global
57
+ 9. ✅ **Plain JSON response** - Beautiful HTML dashboard
58
+ 10. ✅ **No external IP display** - Prominent display in UI
59
+
60
+ ---
61
+
62
+ ## 📋 NEW ENDPOINTS
63
+
64
+ ### **1. GET /** (Dashboard)
65
+ **Response**: Beautiful HTML dashboard with:
66
+ - System uptime
67
+ - External IP (for MOFH whitelist)
68
+ - CPU & Memory usage
69
+ - Request statistics
70
+ - API key usage
71
+ - Available endpoints
72
+ - Developer info
73
+ - Auto-refresh
74
+
75
+ ### **2. GET /health**
76
+ **Response**: JSON
77
+ ```json
78
+ {
79
+ "status": "healthy",
80
+ "uptime_seconds": 12345,
81
+ "timestamp": "2026-01-15T10:30:00",
82
+ "requests": {
83
+ "total": 150,
84
+ "generate": 100,
85
+ "create": 45,
86
+ "errors": 5
87
+ }
88
+ }
89
+ ```
90
+
91
+ ### **3. GET /test**
92
+ **Response**: JSON
93
+ ```json
94
+ {
95
+ "success": true,
96
+ "model": "llama-3.3-70b-versatile",
97
+ "response_length": 234,
98
+ "tokens_used": {"prompt_tokens": 50, "completion_tokens": 100},
99
+ "message": "AI is working correctly!"
100
+ }
101
+ ```
102
+
103
+ ### **4. POST /generate-website** (Enhanced)
104
+ - Now tracks requests
105
+ - Validates input (10-10000 chars)
106
+ - Counts errors
107
+ - Same response format
108
+
109
+ ### **5. POST /create** (Enhanced)
110
+ - Now tracks requests
111
+ - Validates username (3-20 chars)
112
+ - Validates email format
113
+ - Counts errors
114
+ - Same response format
115
+
116
+ ---
117
+
118
+ ## 🎨 DASHBOARD FEATURES
119
+
120
+ ### **Visual Design:**
121
+ - Gradient purple background
122
+ - Glassmorphism cards
123
+ - Smooth animations
124
+ - Hover effects
125
+ - Progress bars
126
+ - Responsive grid layout
127
+ - Auto-refresh (30s)
128
+
129
+ ### **Information Displayed:**
130
+
131
+ **Uptime Card:**
132
+ - Running since timestamp
133
+ - Uptime (hours, minutes, seconds)
134
+ - Total requests
135
+ - Error count
136
+
137
+ **Network Info Card:**
138
+ - Hostname
139
+ - Local IP
140
+ - **External IP (highlighted)**
141
+ - Warning to add IP to MOFH whitelist
142
+
143
+ **System Resources Card:**
144
+ - CPU usage (%)
145
+ - Memory usage (%)
146
+ - Memory used/total (GB)
147
+ - Visual progress bars
148
+
149
+ **AI Configuration Card:**
150
+ - Active models count
151
+ - API keys count
152
+ - Generation count
153
+ - API key usage breakdown
154
+
155
+ **API Endpoints Card:**
156
+ - All available endpoints
157
+ - HTTP methods
158
+ - Descriptions
159
+
160
+ **Developer Info Card:**
161
+ - Developer name
162
+ - GitHub link
163
+ - Portfolio link
164
+ - Version number
165
+
166
+ ---
167
+
168
+ ## 🔧 CONFIGURATION
169
+
170
+ ### **Dependencies (requirements.txt):**
171
+ ```
172
+ fastapi==0.104.1
173
+ uvicorn[standard]==0.24.0
174
+ pydantic==2.5.0
175
+ requests==2.31.0
176
+ psutil==5.9.6
177
+ python-multipart==0.0.6
178
+ ```
179
+
180
+ ### **Install:**
181
+ ```bash
182
+ pip install -r requirements.txt
183
+ ```
184
+
185
+ ### **Run:**
186
+ ```bash
187
+ uvicorn app:app --host 0.0.0.0 --port 7860
188
+ ```
189
+
190
+ ---
191
+
192
+ ## 🧪 TESTING
193
+
194
+ ### **1. Test Dashboard:**
195
+ ```
196
+ http://your-space.hf.space/
197
+ ```
198
+ Expected: Beautiful dashboard with all stats
199
+
200
+ ### **2. Test Health Check:**
201
+ ```
202
+ http://your-space.hf.space/health
203
+ ```
204
+ Expected: JSON with status "healthy"
205
+
206
+ ### **3. Test AI:**
207
+ ```
208
+ http://your-space.hf.space/test
209
+ ```
210
+ Expected: JSON with success=true
211
+
212
+ ### **4. Test Generation:**
213
+ ```bash
214
+ curl -X POST http://your-space.hf.space/generate-website \
215
+ -H "Content-Type: application/json" \
216
+ -d '{
217
+ "prompt": "Create a simple portfolio website",
218
+ "business_type": "portfolio",
219
+ "color_scheme": "modern"
220
+ }'
221
+ ```
222
+ Expected: JSON with success=true and files
223
+
224
+ ### **5. Test Validation:**
225
+ ```bash
226
+ curl -X POST http://your-space.hf.space/generate-website \
227
+ -H "Content-Type: application/json" \
228
+ -d '{"prompt": "short"}'
229
+ ```
230
+ Expected: 422 error (validation failed)
231
+
232
+ ---
233
+
234
+ ## 📊 MONITORING
235
+
236
+ ### **Check System Status:**
237
+ 1. Open dashboard in browser
238
+ 2. Check external IP
239
+ 3. Verify uptime
240
+ 4. Monitor CPU/Memory
241
+ 5. Check request counts
242
+ 6. Review error count
243
+
244
+ ### **Health Monitoring:**
245
+ - Use `/health` endpoint
246
+ - Monitor uptime_seconds
247
+ - Track request counts
248
+ - Alert on high error count
249
+
250
+ ### **AI Testing:**
251
+ - Use `/test` endpoint regularly
252
+ - Verify success=true
253
+ - Check response times
254
+ - Monitor token usage
255
+
256
+ ---
257
+
258
+ ## 🚀 DEPLOYMENT CHECKLIST
259
+
260
+ ### **Before Deploying:**
261
+ - [ ] Update Groq API keys (if needed)
262
+ - [ ] Verify MOFH credentials
263
+ - [ ] Install dependencies
264
+ - [ ] Test locally first
265
+
266
+ ### **After Deploying:**
267
+ - [ ] Visit dashboard
268
+ - [ ] Copy external IP
269
+ - [ ] Add IP to MOFH whitelist
270
+ - [ ] Test `/health` endpoint
271
+ - [ ] Test `/test` endpoint
272
+ - [ ] Test website generation
273
+ - [ ] Monitor for errors
274
+
275
+ ---
276
+
277
+ ## 💡 USAGE TIPS
278
+
279
+ ### **1. External IP for MOFH:**
280
+ - Dashboard shows external IP prominently
281
+ - Copy this IP
282
+ - Add to MOFH API whitelist
283
+ - Required for account creation
284
+
285
+ ### **2. Monitoring:**
286
+ - Dashboard auto-refreshes every 30s
287
+ - Check regularly for errors
288
+ - Monitor CPU/Memory usage
289
+ - Track request patterns
290
+
291
+ ### **3. Testing:**
292
+ - Use `/test` before production
293
+ - Verify AI is responding
294
+ - Check token usage
295
+ - Ensure no errors
296
+
297
+ ### **4. Debugging:**
298
+ - Check error count on dashboard
299
+ - Review logs for details
300
+ - Test with `/test` endpoint
301
+ - Verify API keys are valid
302
+
303
+ ---
304
+
305
+ ## 🎯 WHAT'S IMPROVED
306
+
307
+ ### **Before:**
308
+ - Plain JSON response
309
+ - No uptime tracking
310
+ - No request counting
311
+ - No input validation
312
+ - No health check
313
+ - No test endpoint
314
+ - No external IP display
315
+ - No system monitoring
316
+
317
+ ### **After:**
318
+ - ✅ Beautiful HTML dashboard
319
+ - ✅ Uptime tracking with display
320
+ - ✅ Request counting (total, generate, create, errors)
321
+ - ✅ Input validation (prompt, username, email)
322
+ - ✅ Health check endpoint
323
+ - �� Test endpoint for AI
324
+ - ✅ External IP prominently displayed
325
+ - ✅ System monitoring (CPU, Memory)
326
+ - ✅ API key usage tracking
327
+ - ✅ Auto-refresh dashboard
328
+ - ✅ Responsive design
329
+ - ✅ Error tracking
330
+
331
+ ---
332
+
333
+ ## 📝 NOTES
334
+
335
+ ### **External IP:**
336
+ - Displayed prominently on dashboard
337
+ - Required for MOFH API access
338
+ - Add to MOFH whitelist
339
+ - Changes if server restarts
340
+
341
+ ### **Request Tracking:**
342
+ - Resets on server restart
343
+ - Tracks all requests
344
+ - Separates by type
345
+ - Counts errors
346
+
347
+ ### **System Stats:**
348
+ - Real-time CPU usage
349
+ - Real-time memory usage
350
+ - Updates on refresh
351
+ - Requires psutil
352
+
353
+ ### **Auto-Refresh:**
354
+ - Dashboard refreshes every 30s
355
+ - Keeps stats current
356
+ - Can be disabled if needed
357
+ - Smooth animations
358
+
359
+ ---
360
+
361
+ ## ✨ FINAL STATUS
362
+
363
+ **System Status**: ✅ PRODUCTION READY
364
+
365
+ **Features Added**: 10+
366
+ **Bugs Fixed**: 10+
367
+ **New Endpoints**: 3
368
+ **UI Improvements**: Complete redesign
369
+
370
+ **Ready to deploy to Hugging Face Space!** 🚀
371
+
372
+ ---
373
+
374
+ **Developer**: Pratyush Srivastava
375
+ **Version**: 2026.1.0 (Enhanced)
376
+ **Status**: ✅ ALL IMPROVEMENTS APPLIED
QUICK_SETUP.md ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Quick Setup Guide - GitHub Deployment
2
+
3
+ ## 🚀 5-Minute Setup
4
+
5
+ ### Step 1: Create GitHub App (2 minutes)
6
+ 1. Go to https://github.com/settings/apps/new
7
+ 2. Fill in:
8
+ - **Name:** `Celestine Hosting Deployer`
9
+ - **Homepage:** `https://celestine.indevs.in`
10
+ - **Callback:** `https://celestine.indevs.in/github-deploy`
11
+ - **Webhook:** `https://YOUR-HF-SPACE.hf.space/github/webhook`
12
+ 3. Set permissions:
13
+ - Contents: Read & Write
14
+ - Workflows: Read & Write
15
+ - Secrets: Read & Write
16
+ 4. Click **Create**
17
+
18
+ ### Step 2: Get Credentials (1 minute)
19
+ 1. Copy **App ID** (e.g., `123456`)
20
+ 2. Copy **Client ID** (e.g., `Iv1.abc123def456`)
21
+ 3. Generate **Client Secret** → Copy it
22
+ 4. Generate **Private Key** → Download `.pem` file
23
+
24
+ ### Step 3: Configure HuggingFace (2 minutes)
25
+ 1. Go to your HF Space → Settings → Variables
26
+ 2. Add these secrets:
27
+ ```
28
+ GITHUB_APP_ID = 123456
29
+ GITHUB_CLIENT_ID = Iv1.abc123def456
30
+ GITHUB_CLIENT_SECRET = your-secret-here
31
+ GITHUB_PRIVATE_KEY = -----BEGIN RSA PRIVATE KEY-----...
32
+ ```
33
+
34
+ ### Step 4: Update Frontend
35
+ Edit `htdocs/pages/user/github-deploy.php`:
36
+ ```javascript
37
+ const GITHUB_CLIENT_ID = 'Iv1.abc123def456'; // Your Client ID
38
+ const HF_SPACE_URL = 'https://your-space.hf.space'; // Your HF Space
39
+ ```
40
+
41
+ ### Step 5: Test
42
+ 1. Go to `/github-deploy`
43
+ 2. Click "Connect with GitHub"
44
+ 3. Deploy a repository
45
+ 4. Done! 🎉
46
+
47
+ ---
48
+
49
+ ## 📝 Variables You Need
50
+
51
+ ### From GitHub App:
52
+ ```
53
+ App ID: ____________
54
+ Client ID: Iv1.____________
55
+ Client Secret: ____________
56
+ Private Key: (download .pem file)
57
+ ```
58
+
59
+ ### Your URLs:
60
+ ```
61
+ HuggingFace Space: https://____________.hf.space
62
+ Website: https://celestine.indevs.in
63
+ ```
64
+
65
+ ---
66
+
67
+ ## ✅ That's It!
68
+
69
+ Your GitHub deployment system is now ready to:
70
+ - ✅ Auto-detect 30+ frameworks
71
+ - ✅ Generate workflows automatically
72
+ - ✅ Deploy on every push
73
+ - ✅ Support multiple languages
74
+
75
+ **Full Guide:** See `GITHUB_APP_SETUP_GUIDE.md`
README.md CHANGED
@@ -1,234 +1,234 @@
1
- ---
2
- title: MOFH API Proxy
3
- emoji: 🌐
4
- colorFrom: blue
5
- colorTo: green
6
- sdk: docker
7
- sdk_version: "4.36.0"
8
- python_version: "3.11"
9
- app_file: app.py
10
- pinned: false
11
- ---
12
-
13
- # 🚀 IONA AI + MOFH API Proxy
14
-
15
- **Intelligent Website Generator & MyOwnFreeHost API Proxy**
16
-
17
- ---
18
-
19
- ## ✨ Features
20
-
21
- - 🤖 **AI Website Generation** - Generate complete websites with HTML, CSS, JS, and MySQL
22
- - 🏠 **MOFH Integration** - Create free hosting accounts via API
23
- - 📊 **Beautiful Dashboard** - Real-time system monitoring with uptime display
24
- - 🌐 **External IP Display** - Easy MOFH whitelist configuration
25
- - 🏥 **Health Checks** - Monitor system health and performance
26
- - 🧪 **Test Endpoints** - Verify AI functionality before use
27
-
28
- ---
29
-
30
- ## 🎯 Quick Start
31
-
32
- ### 1. Visit Dashboard
33
- ```
34
- https://your-space.hf.space/
35
- ```
36
-
37
- ### 2. Copy External IP
38
- - Displayed prominently on dashboard
39
- - Add to MOFH API whitelist
40
-
41
- ### 3. Test AI
42
- ```
43
- https://your-space.hf.space/test
44
- ```
45
-
46
- ### 4. Generate Website
47
- ```bash
48
- curl -X POST https://your-space.hf.space/generate-website \
49
- -H "Content-Type: application/json" \
50
- -d '{
51
- "prompt": "Create a modern portfolio website",
52
- "business_type": "portfolio",
53
- "color_scheme": "modern"
54
- }'
55
- ```
56
-
57
- ---
58
-
59
- ## 📡 API Endpoints
60
-
61
- | Method | Endpoint | Description |
62
- |--------|----------|-------------|
63
- | GET | `/` | System dashboard (HTML) |
64
- | GET | `/health` | Health check (JSON) |
65
- | GET | `/test` | Test AI generation |
66
- | POST | `/generate-website` | Generate website with AI |
67
- | POST | `/create` | Create MOFH hosting account |
68
-
69
- ---
70
-
71
- ## 🔧 Configuration
72
-
73
- ### Environment Variables
74
- - `GROQ_API_KEYS` - Groq AI API keys (4 keys for load balancing)
75
- - `MOFH_API_USERNAME` - MOFH API username
76
- - `MOFH_API_PASSWORD` - MOFH API password
77
-
78
- ### AI Models (2026)
79
- - `llama-3.1-8b-instant` - Fastest (131K context)
80
- - `llama-3.3-70b-versatile` - Best quality
81
- - `qwen/qwen3-32b` - Large output (40K tokens)
82
- - `meta-llama/llama-4-scout-17b-16e-instruct` - New Llama 4
83
-
84
- ---
85
-
86
- ## 📊 Dashboard Features
87
-
88
- - ⏱️ **Uptime Tracking** - Running since, uptime duration
89
- - 🌐 **Network Info** - Hostname, local IP, external IP
90
- - 💻 **System Resources** - CPU usage, memory usage with progress bars
91
- - 🤖 **AI Configuration** - Active models, API keys, request counts
92
- - 📈 **Request Statistics** - Total, generate, create, errors
93
- - 🔄 **Auto-Refresh** - Updates every 30 seconds
94
-
95
- ---
96
-
97
- ## 🧪 Testing
98
-
99
- ### Health Check
100
- ```bash
101
- curl https://your-space.hf.space/health
102
- ```
103
-
104
- ### AI Test
105
- ```bash
106
- curl https://your-space.hf.space/test
107
- ```
108
-
109
- ### Generate Website
110
- ```bash
111
- curl -X POST https://your-space.hf.space/generate-website \
112
- -H "Content-Type: application/json" \
113
- -d '{
114
- "prompt": "Create a simple landing page for a tech startup",
115
- "business_type": "landing",
116
- "color_scheme": "modern",
117
- "include_database": false,
118
- "features": ["contact_form", "testimonials"]
119
- }'
120
- ```
121
-
122
- ---
123
-
124
- ## 📝 Response Format
125
-
126
- ### Success Response
127
- ```json
128
- {
129
- "success": true,
130
- "model_used": "llama-3.3-70b-versatile",
131
- "files": {
132
- "html": "<!DOCTYPE html>...",
133
- "css": "body { ... }",
134
- "js": "console.log('...');",
135
- "sql": "CREATE TABLE...",
136
- "config": "<?php...",
137
- "readme": "# Setup Guide..."
138
- },
139
- "tokens_used": {
140
- "prompt_tokens": 1234,
141
- "completion_tokens": 5678
142
- },
143
- "generation_time": 1234567890
144
- }
145
- ```
146
-
147
- ### Error Response
148
- ```json
149
- {
150
- "detail": "Error message here"
151
- }
152
- ```
153
-
154
- ---
155
-
156
- ## 🔒 Security
157
-
158
- - ✅ Input validation (Pydantic)
159
- - ✅ Prompt length limits (10-10000 chars)
160
- - ✅ Username validation (3-20 chars)
161
- - ✅ Email format validation
162
- - ✅ Error handling and logging
163
- - ✅ Request tracking
164
-
165
- ---
166
-
167
- ## 📈 Monitoring
168
-
169
- ### Dashboard Metrics
170
- - Uptime duration
171
- - Total requests
172
- - Error count
173
- - CPU usage
174
- - Memory usage
175
- - API key usage
176
-
177
- ### Health Endpoint
178
- ```json
179
- {
180
- "status": "healthy",
181
- "uptime_seconds": 12345,
182
- "timestamp": "2026-01-15T10:30:00",
183
- "requests": {
184
- "total": 150,
185
- "generate": 100,
186
- "create": 45,
187
- "errors": 5
188
- }
189
- }
190
- ```
191
-
192
- ---
193
-
194
- ## 🛠️ Development
195
-
196
- ### Install Dependencies
197
- ```bash
198
- pip install -r requirements.txt
199
- ```
200
-
201
- ### Run Locally
202
- ```bash
203
- uvicorn app:app --host 0.0.0.0 --port 7860 --reload
204
- ```
205
-
206
- ### Deploy to HF Space
207
- 1. Create new Space on Hugging Face
208
- 2. Upload `app.py` and `requirements.txt`
209
- 3. Set Space SDK to "Docker" or "Gradio"
210
- 4. Space will auto-deploy
211
-
212
- ---
213
-
214
- ## 👨‍💻 Developer
215
-
216
- **Pratyush Srivastava**
217
- - GitHub: [@pratyush](https://github.com/pratyush)
218
- - Portfolio: [pratyush.dev](https://pratyush.dev)
219
-
220
- ---
221
-
222
- ## 📄 License
223
-
224
- MIT License - Feel free to use and modify
225
-
226
- ---
227
-
228
- ## 🎉 Version
229
-
230
- **2026.1.0** - Enhanced with uptime dashboard, external IP display, and comprehensive monitoring
231
-
232
- ---
233
-
234
- **Status**: ✅ Production Ready (Updated 2026-03-30)
 
1
+ ---
2
+ title: MOFH API Proxy
3
+ emoji: 🌐
4
+ colorFrom: blue
5
+ colorTo: green
6
+ sdk: docker
7
+ sdk_version: "4.36.0"
8
+ python_version: "3.11"
9
+ app_file: app.py
10
+ pinned: false
11
+ ---
12
+
13
+ # 🚀 IONA AI + MOFH API Proxy
14
+
15
+ **Intelligent Website Generator & MyOwnFreeHost API Proxy**
16
+
17
+ ---
18
+
19
+ ## ✨ Features
20
+
21
+ - 🤖 **AI Website Generation** - Generate complete websites with HTML, CSS, JS, and MySQL
22
+ - 🏠 **MOFH Integration** - Create free hosting accounts via API
23
+ - 📊 **Beautiful Dashboard** - Real-time system monitoring with uptime display
24
+ - 🌐 **External IP Display** - Easy MOFH whitelist configuration
25
+ - 🏥 **Health Checks** - Monitor system health and performance
26
+ - 🧪 **Test Endpoints** - Verify AI functionality before use
27
+
28
+ ---
29
+
30
+ ## 🎯 Quick Start
31
+
32
+ ### 1. Visit Dashboard
33
+ ```
34
+ https://your-space.hf.space/
35
+ ```
36
+
37
+ ### 2. Copy External IP
38
+ - Displayed prominently on dashboard
39
+ - Add to MOFH API whitelist
40
+
41
+ ### 3. Test AI
42
+ ```
43
+ https://your-space.hf.space/test
44
+ ```
45
+
46
+ ### 4. Generate Website
47
+ ```bash
48
+ curl -X POST https://your-space.hf.space/generate-website \
49
+ -H "Content-Type: application/json" \
50
+ -d '{
51
+ "prompt": "Create a modern portfolio website",
52
+ "business_type": "portfolio",
53
+ "color_scheme": "modern"
54
+ }'
55
+ ```
56
+
57
+ ---
58
+
59
+ ## 📡 API Endpoints
60
+
61
+ | Method | Endpoint | Description |
62
+ |--------|----------|-------------|
63
+ | GET | `/` | System dashboard (HTML) |
64
+ | GET | `/health` | Health check (JSON) |
65
+ | GET | `/test` | Test AI generation |
66
+ | POST | `/generate-website` | Generate website with AI |
67
+ | POST | `/create` | Create MOFH hosting account |
68
+
69
+ ---
70
+
71
+ ## 🔧 Configuration
72
+
73
+ ### Environment Variables
74
+ - `GROQ_API_KEYS` - Groq AI API keys (4 keys for load balancing)
75
+ - `MOFH_API_USERNAME` - MOFH API username
76
+ - `MOFH_API_PASSWORD` - MOFH API password
77
+
78
+ ### AI Models (2026)
79
+ - `llama-3.1-8b-instant` - Fastest (131K context)
80
+ - `llama-3.3-70b-versatile` - Best quality
81
+ - `qwen/qwen3-32b` - Large output (40K tokens)
82
+ - `meta-llama/llama-4-scout-17b-16e-instruct` - New Llama 4
83
+
84
+ ---
85
+
86
+ ## 📊 Dashboard Features
87
+
88
+ - ⏱️ **Uptime Tracking** - Running since, uptime duration
89
+ - 🌐 **Network Info** - Hostname, local IP, external IP
90
+ - 💻 **System Resources** - CPU usage, memory usage with progress bars
91
+ - 🤖 **AI Configuration** - Active models, API keys, request counts
92
+ - 📈 **Request Statistics** - Total, generate, create, errors
93
+ - 🔄 **Auto-Refresh** - Updates every 30 seconds
94
+
95
+ ---
96
+
97
+ ## 🧪 Testing
98
+
99
+ ### Health Check
100
+ ```bash
101
+ curl https://your-space.hf.space/health
102
+ ```
103
+
104
+ ### AI Test
105
+ ```bash
106
+ curl https://your-space.hf.space/test
107
+ ```
108
+
109
+ ### Generate Website
110
+ ```bash
111
+ curl -X POST https://your-space.hf.space/generate-website \
112
+ -H "Content-Type: application/json" \
113
+ -d '{
114
+ "prompt": "Create a simple landing page for a tech startup",
115
+ "business_type": "landing",
116
+ "color_scheme": "modern",
117
+ "include_database": false,
118
+ "features": ["contact_form", "testimonials"]
119
+ }'
120
+ ```
121
+
122
+ ---
123
+
124
+ ## 📝 Response Format
125
+
126
+ ### Success Response
127
+ ```json
128
+ {
129
+ "success": true,
130
+ "model_used": "llama-3.3-70b-versatile",
131
+ "files": {
132
+ "html": "<!DOCTYPE html>...",
133
+ "css": "body { ... }",
134
+ "js": "console.log('...');",
135
+ "sql": "CREATE TABLE...",
136
+ "config": "<?php...",
137
+ "readme": "# Setup Guide..."
138
+ },
139
+ "tokens_used": {
140
+ "prompt_tokens": 1234,
141
+ "completion_tokens": 5678
142
+ },
143
+ "generation_time": 1234567890
144
+ }
145
+ ```
146
+
147
+ ### Error Response
148
+ ```json
149
+ {
150
+ "detail": "Error message here"
151
+ }
152
+ ```
153
+
154
+ ---
155
+
156
+ ## 🔒 Security
157
+
158
+ - ✅ Input validation (Pydantic)
159
+ - ✅ Prompt length limits (10-10000 chars)
160
+ - ✅ Username validation (3-20 chars)
161
+ - ✅ Email format validation
162
+ - ✅ Error handling and logging
163
+ - ✅ Request tracking
164
+
165
+ ---
166
+
167
+ ## 📈 Monitoring
168
+
169
+ ### Dashboard Metrics
170
+ - Uptime duration
171
+ - Total requests
172
+ - Error count
173
+ - CPU usage
174
+ - Memory usage
175
+ - API key usage
176
+
177
+ ### Health Endpoint
178
+ ```json
179
+ {
180
+ "status": "healthy",
181
+ "uptime_seconds": 12345,
182
+ "timestamp": "2026-01-15T10:30:00",
183
+ "requests": {
184
+ "total": 150,
185
+ "generate": 100,
186
+ "create": 45,
187
+ "errors": 5
188
+ }
189
+ }
190
+ ```
191
+
192
+ ---
193
+
194
+ ## 🛠️ Development
195
+
196
+ ### Install Dependencies
197
+ ```bash
198
+ pip install -r requirements.txt
199
+ ```
200
+
201
+ ### Run Locally
202
+ ```bash
203
+ uvicorn app:app --host 0.0.0.0 --port 7860 --reload
204
+ ```
205
+
206
+ ### Deploy to HF Space
207
+ 1. Create new Space on Hugging Face
208
+ 2. Upload `app.py` and `requirements.txt`
209
+ 3. Set Space SDK to "Docker" or "Gradio"
210
+ 4. Space will auto-deploy
211
+
212
+ ---
213
+
214
+ ## 👨‍💻 Developer
215
+
216
+ **Pratyush Srivastava**
217
+ - GitHub: [@pratyush](https://github.com/pratyush)
218
+ - Portfolio: [pratyush.dev](https://pratyush.dev)
219
+
220
+ ---
221
+
222
+ ## 📄 License
223
+
224
+ MIT License - Feel free to use and modify
225
+
226
+ ---
227
+
228
+ ## 🎉 Version
229
+
230
+ **2026.1.0** - Enhanced with uptime dashboard, external IP display, and comprehensive monitoring
231
+
232
+ ---
233
+
234
+ **Status**: ✅ Production Ready (Updated 2026-03-30)
STATUS.txt CHANGED
@@ -1,58 +1,58 @@
1
- ✓ IONA AI - PRODUCTION READY
2
- =============================
3
-
4
- STATUS: ALL SYSTEMS GO ✓
5
-
6
- Files (5):
7
- 1. app.py - Main FastAPI application (TESTED ✓)
8
- 2. requirements.txt - Python dependencies (VERIFIED ✓)
9
- 3. Dockerfile - Container configuration (READY ✓)
10
- 4. README.md - Documentation (COMPLETE ✓)
11
- 5. DEPLOY.txt - Deployment instructions (READY ✓)
12
-
13
- Endpoints (11):
14
- ✓ GET / - Beautiful dashboard with system stats
15
- ✓ GET /health - Health check endpoint
16
- ✓ GET /test - Test AI generation
17
- ✓ POST /generate-website - Generate complete website
18
- ✓ POST /create - Create MOFH hosting account
19
- ✓ POST /deploy-ftp - Deploy files via FTP
20
- ✓ POST /generate-and-deploy - Combined generation + deployment
21
- ✓ GET /docs - Auto-generated API docs
22
- ✓ GET /redoc - Alternative API docs
23
- ✓ GET /openapi.json - OpenAPI schema
24
- ✓ GET /docs/oauth2-redirect - OAuth redirect
25
-
26
- Features:
27
- ✓ AI website generation with Groq API
28
- ✓ MOFH account creation
29
- ✓ Load-balanced API keys (4 keys)
30
- ✓ Comprehensive error handling
31
- ✓ JSON parsing with fallbacks
32
- ✓ Request tracking and logging
33
- ✓ System monitoring (CPU, Memory, Uptime)
34
- ✓ External IP detection
35
- ✓ Beautiful responsive dashboard
36
- ✓ Input validation with Pydantic
37
- ✓ Security best practices
38
-
39
- Tested:
40
- ✓ Python syntax check - PASSED
41
- ✓ Import test - PASSED
42
- ✓ Endpoint registration - PASSED
43
- ✓ Dependencies check - PASSED
44
-
45
- Ready for:
46
- ✓ Hugging Face Spaces deployment
47
- ✓ Docker deployment
48
- ✓ Local development
49
- ✓ Production use
50
-
51
- Next Steps:
52
- 1. Upload to Hugging Face Spaces
53
- 2. Copy External IP from dashboard
54
- 3. Add IP to MOFH whitelist
55
- 4. Update PHP with HF Space URL
56
- 5. Start generating websites!
57
-
58
- NO ISSUES FOUND - DEPLOY NOW! 🚀
 
1
+ ✓ IONA AI - PRODUCTION READY
2
+ =============================
3
+
4
+ STATUS: ALL SYSTEMS GO ✓
5
+
6
+ Files (5):
7
+ 1. app.py - Main FastAPI application (TESTED ✓)
8
+ 2. requirements.txt - Python dependencies (VERIFIED ✓)
9
+ 3. Dockerfile - Container configuration (READY ✓)
10
+ 4. README.md - Documentation (COMPLETE ✓)
11
+ 5. DEPLOY.txt - Deployment instructions (READY ✓)
12
+
13
+ Endpoints (11):
14
+ ✓ GET / - Beautiful dashboard with system stats
15
+ ✓ GET /health - Health check endpoint
16
+ ✓ GET /test - Test AI generation
17
+ ✓ POST /generate-website - Generate complete website
18
+ ✓ POST /create - Create MOFH hosting account
19
+ ✓ POST /deploy-ftp - Deploy files via FTP
20
+ ✓ POST /generate-and-deploy - Combined generation + deployment
21
+ ✓ GET /docs - Auto-generated API docs
22
+ ✓ GET /redoc - Alternative API docs
23
+ ✓ GET /openapi.json - OpenAPI schema
24
+ ✓ GET /docs/oauth2-redirect - OAuth redirect
25
+
26
+ Features:
27
+ ✓ AI website generation with Groq API
28
+ ✓ MOFH account creation
29
+ ✓ Load-balanced API keys (4 keys)
30
+ ✓ Comprehensive error handling
31
+ ✓ JSON parsing with fallbacks
32
+ ✓ Request tracking and logging
33
+ ✓ System monitoring (CPU, Memory, Uptime)
34
+ ✓ External IP detection
35
+ ✓ Beautiful responsive dashboard
36
+ ✓ Input validation with Pydantic
37
+ ✓ Security best practices
38
+
39
+ Tested:
40
+ ✓ Python syntax check - PASSED
41
+ ✓ Import test - PASSED
42
+ ✓ Endpoint registration - PASSED
43
+ ✓ Dependencies check - PASSED
44
+
45
+ Ready for:
46
+ ✓ Hugging Face Spaces deployment
47
+ ✓ Docker deployment
48
+ ✓ Local development
49
+ ✓ Production use
50
+
51
+ Next Steps:
52
+ 1. Upload to Hugging Face Spaces
53
+ 2. Copy External IP from dashboard
54
+ 3. Add IP to MOFH whitelist
55
+ 4. Update PHP with HF Space URL
56
+ 5. Start generating websites!
57
+
58
+ NO ISSUES FOUND - DEPLOY NOW! 🚀
app.py CHANGED
The diff for this file is too large to render. See raw diff
 
github_deploy.py ADDED
@@ -0,0 +1,937 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # GitHub Deployment Module for Celestine Hosting
2
+ # Handles GitHub App integration, workflow injection, and deployment tracking
3
+
4
+ import requests
5
+ import base64
6
+ import json
7
+ import time
8
+ import jwt
9
+ from typing import Dict, List, Optional, Tuple
10
+ from datetime import datetime, timedelta
11
+ from nacl import encoding, public
12
+ import logging
13
+
14
+ logger = logging.getLogger(__name__)
15
+
16
+ class GitHubDeployment:
17
+ """
18
+ Manages GitHub deployments for Celestine Hosting
19
+ - GitHub App authentication
20
+ - Repository access
21
+ - Workflow file injection
22
+ - Deployment status tracking
23
+ """
24
+
25
+ def __init__(self, app_id: str, client_id: str, client_secret: str, private_key: str):
26
+ self.app_id = app_id
27
+ self.client_id = client_id
28
+ self.client_secret = client_secret
29
+ self.private_key = private_key
30
+ self.github_api = "https://api.github.com"
31
+
32
+ def generate_jwt(self) -> str:
33
+ """Generate JWT for GitHub App authentication"""
34
+ now = int(time.time())
35
+ payload = {
36
+ 'iat': now - 60, # Issued 60 seconds in the past
37
+ 'exp': now + (10 * 60), # Expires in 10 minutes
38
+ 'iss': self.app_id
39
+ }
40
+
41
+ return jwt.encode(payload, self.private_key, algorithm='RS256')
42
+
43
+ def get_installation_access_token(self, installation_id: str) -> str:
44
+ """Get installation access token for a specific installation"""
45
+ jwt_token = self.generate_jwt()
46
+
47
+ headers = {
48
+ 'Authorization': f'Bearer {jwt_token}',
49
+ 'Accept': 'application/vnd.github.v3+json'
50
+ }
51
+
52
+ response = requests.post(
53
+ f'{self.github_api}/app/installations/{installation_id}/access_tokens',
54
+ headers=headers,
55
+ timeout=30
56
+ )
57
+
58
+ if response.status_code != 201:
59
+ raise Exception(f"Failed to get access token: {response.text}")
60
+
61
+ return response.json()['token']
62
+
63
+ def exchange_code_for_token(self, code: str) -> Dict:
64
+ """Exchange OAuth code for access token"""
65
+ response = requests.post(
66
+ 'https://github.com/login/oauth/access_token',
67
+ headers={'Accept': 'application/json'},
68
+ data={
69
+ 'client_id': self.client_id,
70
+ 'client_secret': self.client_secret,
71
+ 'code': code
72
+ },
73
+ timeout=30
74
+ )
75
+
76
+ if response.status_code != 200:
77
+ raise Exception(f"Failed to exchange code: {response.text}")
78
+
79
+ return response.json()
80
+
81
+ def get_user_repos(self, access_token: str) -> List[Dict]:
82
+ """Get user's repositories"""
83
+ headers = {
84
+ 'Authorization': f'token {access_token}',
85
+ 'Accept': 'application/vnd.github.v3+json'
86
+ }
87
+
88
+ response = requests.get(
89
+ f'{self.github_api}/user/repos',
90
+ headers=headers,
91
+ params={'per_page': 100, 'sort': 'updated'},
92
+ timeout=30
93
+ )
94
+
95
+ if response.status_code != 200:
96
+ raise Exception(f"Failed to get repositories: {response.text}")
97
+
98
+ return response.json()
99
+
100
+ def get_repo_public_key(self, owner: str, repo: str, access_token: str) -> Tuple[str, str]:
101
+ """Get repository's public key for secrets encryption"""
102
+ headers = {
103
+ 'Authorization': f'token {access_token}',
104
+ 'Accept': 'application/vnd.github.v3+json'
105
+ }
106
+
107
+ response = requests.get(
108
+ f'{self.github_api}/repos/{owner}/{repo}/actions/secrets/public-key',
109
+ headers=headers,
110
+ timeout=30
111
+ )
112
+
113
+ if response.status_code != 200:
114
+ raise Exception(f"Failed to get public key: {response.text}")
115
+
116
+ data = response.json()
117
+ return data['key'], data['key_id']
118
+
119
+ def encrypt_secret(self, public_key: str, secret_value: str) -> str:
120
+ """Encrypt a secret using the repository's public key"""
121
+ public_key_obj = public.PublicKey(public_key.encode("utf-8"), encoding.Base64Encoder)
122
+ sealed_box = public.SealedBox(public_key_obj)
123
+ encrypted = sealed_box.encrypt(secret_value.encode("utf-8"))
124
+ return base64.b64encode(encrypted).decode("utf-8")
125
+
126
+ def create_or_update_secret(self, owner: str, repo: str, secret_name: str,
127
+ secret_value: str, access_token: str) -> bool:
128
+ """Create or update a repository secret"""
129
+ try:
130
+ # Get public key
131
+ public_key, key_id = self.get_repo_public_key(owner, repo, access_token)
132
+
133
+ # Encrypt secret
134
+ encrypted_value = self.encrypt_secret(public_key, secret_value)
135
+
136
+ # Create/update secret
137
+ headers = {
138
+ 'Authorization': f'token {access_token}',
139
+ 'Accept': 'application/vnd.github.v3+json'
140
+ }
141
+
142
+ response = requests.put(
143
+ f'{self.github_api}/repos/{owner}/{repo}/actions/secrets/{secret_name}',
144
+ headers=headers,
145
+ json={
146
+ 'encrypted_value': encrypted_value,
147
+ 'key_id': key_id
148
+ },
149
+ timeout=30
150
+ )
151
+
152
+ return response.status_code in [201, 204]
153
+ except Exception as e:
154
+ logger.error(f"Failed to create secret {secret_name}: {e}")
155
+ return False
156
+
157
+ def detect_project_type(self, owner: str, repo: str, access_token: str) -> Dict:
158
+ """
159
+ Enhanced project type detection
160
+ Supports: React, Vue, Angular, Next.js, Nuxt, Svelte, Gatsby, Astro,
161
+ Hugo, Jekyll, Python, PHP, Ruby, Go, Rust, and 30+ frameworks
162
+ """
163
+ headers = {
164
+ 'Authorization': f'token {access_token}',
165
+ 'Accept': 'application/vnd.github.v3+json'
166
+ }
167
+
168
+ # Get repository contents
169
+ response = requests.get(
170
+ f'{self.github_api}/repos/{owner}/{repo}/contents',
171
+ headers=headers,
172
+ timeout=30
173
+ )
174
+
175
+ if response.status_code != 200:
176
+ return {
177
+ 'type': 'static',
178
+ 'build_command': '',
179
+ 'output_dir': '.',
180
+ 'install_command': '',
181
+ 'language': 'html'
182
+ }
183
+
184
+ files = {item['name']: item for item in response.json() if item['type'] == 'file'}
185
+
186
+ # Priority 1: Check for .celestine.yml (custom configuration)
187
+ if '.celestine.yml' in files or '.celestine.yaml' in files:
188
+ try:
189
+ config_file = '.celestine.yml' if '.celestine.yml' in files else '.celestine.yaml'
190
+ config_response = requests.get(files[config_file]['download_url'], timeout=30)
191
+ import yaml
192
+ config = yaml.safe_load(config_response.text)
193
+
194
+ return {
195
+ 'type': config.get('project', {}).get('type', 'custom'),
196
+ 'build_command': config.get('build', {}).get('command', ''),
197
+ 'output_dir': config.get('build', {}).get('output', 'dist'),
198
+ 'install_command': config.get('build', {}).get('install', ''),
199
+ 'language': config.get('project', {}).get('language', 'unknown'),
200
+ 'node_version': config.get('runtime', {}).get('node', '18'),
201
+ 'python_version': config.get('runtime', {}).get('python', '3.11'),
202
+ 'php_version': config.get('runtime', {}).get('php', '8.2')
203
+ }
204
+ except Exception as e:
205
+ logger.warning(f"Failed to parse .celestine.yml: {e}")
206
+
207
+ # Priority 2: Node.js/JavaScript/TypeScript projects
208
+ if 'package.json' in files:
209
+ try:
210
+ pkg_response = requests.get(files['package.json']['download_url'], timeout=30)
211
+ package_json = pkg_response.json()
212
+
213
+ dependencies = package_json.get('dependencies', {})
214
+ dev_dependencies = package_json.get('devDependencies', {})
215
+ scripts = package_json.get('scripts', {})
216
+
217
+ # Next.js
218
+ if 'next' in dependencies or 'next' in dev_dependencies:
219
+ return {
220
+ 'type': 'nextjs',
221
+ 'build_command': 'npm run build && npm run export',
222
+ 'output_dir': 'out',
223
+ 'install_command': 'npm ci',
224
+ 'language': 'javascript',
225
+ 'node_version': '18'
226
+ }
227
+
228
+ # Nuxt.js
229
+ elif 'nuxt' in dependencies or 'nuxt' in dev_dependencies:
230
+ return {
231
+ 'type': 'nuxt',
232
+ 'build_command': 'npm run generate',
233
+ 'output_dir': 'dist',
234
+ 'install_command': 'npm ci',
235
+ 'language': 'javascript',
236
+ 'node_version': '18'
237
+ }
238
+
239
+ # Gatsby
240
+ elif 'gatsby' in dependencies or 'gatsby' in dev_dependencies:
241
+ return {
242
+ 'type': 'gatsby',
243
+ 'build_command': 'npm run build',
244
+ 'output_dir': 'public',
245
+ 'install_command': 'npm ci',
246
+ 'language': 'javascript',
247
+ 'node_version': '18'
248
+ }
249
+
250
+ # Astro
251
+ elif 'astro' in dependencies or 'astro' in dev_dependencies:
252
+ return {
253
+ 'type': 'astro',
254
+ 'build_command': 'npm run build',
255
+ 'output_dir': 'dist',
256
+ 'install_command': 'npm ci',
257
+ 'language': 'javascript',
258
+ 'node_version': '18'
259
+ }
260
+
261
+ # Docusaurus
262
+ elif '@docusaurus/core' in dependencies:
263
+ return {
264
+ 'type': 'docusaurus',
265
+ 'build_command': 'npm run build',
266
+ 'output_dir': 'build',
267
+ 'install_command': 'npm ci',
268
+ 'language': 'javascript',
269
+ 'node_version': '18'
270
+ }
271
+
272
+ # Eleventy (11ty)
273
+ elif '@11ty/eleventy' in dependencies or '@11ty/eleventy' in dev_dependencies:
274
+ return {
275
+ 'type': 'eleventy',
276
+ 'build_command': 'npm run build',
277
+ 'output_dir': '_site',
278
+ 'install_command': 'npm ci',
279
+ 'language': 'javascript',
280
+ 'node_version': '18'
281
+ }
282
+
283
+ # VuePress
284
+ elif 'vuepress' in dependencies or 'vuepress' in dev_dependencies:
285
+ return {
286
+ 'type': 'vuepress',
287
+ 'build_command': 'npm run build',
288
+ 'output_dir': 'docs/.vuepress/dist',
289
+ 'install_command': 'npm ci',
290
+ 'language': 'javascript',
291
+ 'node_version': '18'
292
+ }
293
+
294
+ # Hexo
295
+ elif 'hexo' in dependencies or 'hexo' in dev_dependencies:
296
+ return {
297
+ 'type': 'hexo',
298
+ 'build_command': 'npm run build',
299
+ 'output_dir': 'public',
300
+ 'install_command': 'npm ci',
301
+ 'language': 'javascript',
302
+ 'node_version': '18'
303
+ }
304
+
305
+ # React
306
+ elif 'react' in dependencies:
307
+ build_cmd = scripts.get('build', 'npm run build')
308
+ return {
309
+ 'type': 'react',
310
+ 'build_command': build_cmd,
311
+ 'output_dir': 'build',
312
+ 'install_command': 'npm ci',
313
+ 'language': 'javascript',
314
+ 'node_version': '18'
315
+ }
316
+
317
+ # Vue.js
318
+ elif 'vue' in dependencies:
319
+ return {
320
+ 'type': 'vue',
321
+ 'build_command': 'npm run build',
322
+ 'output_dir': 'dist',
323
+ 'install_command': 'npm ci',
324
+ 'language': 'javascript',
325
+ 'node_version': '18'
326
+ }
327
+
328
+ # Angular
329
+ elif '@angular/core' in dependencies:
330
+ return {
331
+ 'type': 'angular',
332
+ 'build_command': 'npm run build -- --configuration production',
333
+ 'output_dir': 'dist',
334
+ 'install_command': 'npm ci',
335
+ 'language': 'typescript',
336
+ 'node_version': '18'
337
+ }
338
+
339
+ # Svelte/SvelteKit
340
+ elif 'svelte' in dependencies or 'svelte' in dev_dependencies:
341
+ if '@sveltejs/kit' in dependencies or '@sveltejs/kit' in dev_dependencies:
342
+ return {
343
+ 'type': 'sveltekit',
344
+ 'build_command': 'npm run build',
345
+ 'output_dir': 'build',
346
+ 'install_command': 'npm ci',
347
+ 'language': 'javascript',
348
+ 'node_version': '18'
349
+ }
350
+ return {
351
+ 'type': 'svelte',
352
+ 'build_command': 'npm run build',
353
+ 'output_dir': 'public',
354
+ 'install_command': 'npm ci',
355
+ 'language': 'javascript',
356
+ 'node_version': '18'
357
+ }
358
+
359
+ # Vite
360
+ elif 'vite' in dev_dependencies:
361
+ return {
362
+ 'type': 'vite',
363
+ 'build_command': 'npm run build',
364
+ 'output_dir': 'dist',
365
+ 'install_command': 'npm ci',
366
+ 'language': 'javascript',
367
+ 'node_version': '18'
368
+ }
369
+
370
+ # Generic Node.js
371
+ else:
372
+ return {
373
+ 'type': 'nodejs',
374
+ 'build_command': scripts.get('build', 'npm run build'),
375
+ 'output_dir': 'dist',
376
+ 'install_command': 'npm ci',
377
+ 'language': 'javascript',
378
+ 'node_version': '18'
379
+ }
380
+ except Exception as e:
381
+ logger.warning(f"Failed to parse package.json: {e}")
382
+
383
+ # Priority 3: Python projects
384
+ if 'requirements.txt' in files or 'pyproject.toml' in files:
385
+ # Django
386
+ if 'manage.py' in files:
387
+ return {
388
+ 'type': 'django',
389
+ 'build_command': 'python manage.py collectstatic --noinput',
390
+ 'output_dir': 'staticfiles',
391
+ 'install_command': 'pip install -r requirements.txt',
392
+ 'language': 'python',
393
+ 'python_version': '3.11'
394
+ }
395
+
396
+ # Flask
397
+ elif 'app.py' in files or 'wsgi.py' in files:
398
+ return {
399
+ 'type': 'flask',
400
+ 'build_command': 'python build.py',
401
+ 'output_dir': 'build',
402
+ 'install_command': 'pip install -r requirements.txt',
403
+ 'language': 'python',
404
+ 'python_version': '3.11'
405
+ }
406
+
407
+ # Generic Python
408
+ else:
409
+ return {
410
+ 'type': 'python',
411
+ 'build_command': 'python build.py',
412
+ 'output_dir': 'dist',
413
+ 'install_command': 'pip install -r requirements.txt',
414
+ 'language': 'python',
415
+ 'python_version': '3.11'
416
+ }
417
+
418
+ # Priority 4: PHP projects
419
+ if 'composer.json' in files:
420
+ try:
421
+ composer_response = requests.get(files['composer.json']['download_url'], timeout=30)
422
+ composer_json = composer_response.json()
423
+
424
+ require = composer_json.get('require', {})
425
+
426
+ # Laravel
427
+ if 'laravel/framework' in require:
428
+ return {
429
+ 'type': 'laravel',
430
+ 'build_command': 'composer install --no-dev --optimize-autoloader && npm run build',
431
+ 'output_dir': 'public',
432
+ 'install_command': 'composer install',
433
+ 'language': 'php',
434
+ 'php_version': '8.2',
435
+ 'node_version': '18'
436
+ }
437
+
438
+ # Symfony
439
+ elif 'symfony/framework-bundle' in require:
440
+ return {
441
+ 'type': 'symfony',
442
+ 'build_command': 'composer install --no-dev --optimize-autoloader && npm run build',
443
+ 'output_dir': 'public',
444
+ 'install_command': 'composer install',
445
+ 'language': 'php',
446
+ 'php_version': '8.2',
447
+ 'node_version': '18'
448
+ }
449
+
450
+ # CodeIgniter
451
+ elif 'codeigniter4/framework' in require:
452
+ return {
453
+ 'type': 'codeigniter',
454
+ 'build_command': 'composer install --no-dev',
455
+ 'output_dir': 'public',
456
+ 'install_command': 'composer install',
457
+ 'language': 'php',
458
+ 'php_version': '8.1'
459
+ }
460
+
461
+ # Generic PHP
462
+ else:
463
+ return {
464
+ 'type': 'php',
465
+ 'build_command': 'composer install --no-dev',
466
+ 'output_dir': '.',
467
+ 'install_command': 'composer install',
468
+ 'language': 'php',
469
+ 'php_version': '8.1'
470
+ }
471
+ except Exception as e:
472
+ logger.warning(f"Failed to parse composer.json: {e}")
473
+
474
+ # Priority 5: Ruby projects
475
+ if 'Gemfile' in files:
476
+ # Jekyll
477
+ if '_config.yml' in files:
478
+ return {
479
+ 'type': 'jekyll',
480
+ 'build_command': 'bundle exec jekyll build',
481
+ 'output_dir': '_site',
482
+ 'install_command': 'bundle install',
483
+ 'language': 'ruby',
484
+ 'ruby_version': '3.2'
485
+ }
486
+
487
+ # Middleman
488
+ elif 'config.rb' in files:
489
+ return {
490
+ 'type': 'middleman',
491
+ 'build_command': 'bundle exec middleman build',
492
+ 'output_dir': 'build',
493
+ 'install_command': 'bundle install',
494
+ 'language': 'ruby',
495
+ 'ruby_version': '3.2'
496
+ }
497
+
498
+ # Generic Ruby
499
+ else:
500
+ return {
501
+ 'type': 'ruby',
502
+ 'build_command': 'bundle exec rake build',
503
+ 'output_dir': 'build',
504
+ 'install_command': 'bundle install',
505
+ 'language': 'ruby',
506
+ 'ruby_version': '3.2'
507
+ }
508
+
509
+ # Priority 6: Go projects
510
+ if 'go.mod' in files:
511
+ # Hugo
512
+ if 'config.toml' in files or 'config.yaml' in files or 'hugo.toml' in files:
513
+ return {
514
+ 'type': 'hugo',
515
+ 'build_command': 'hugo --minify',
516
+ 'output_dir': 'public',
517
+ 'install_command': '',
518
+ 'language': 'go',
519
+ 'hugo_version': 'latest'
520
+ }
521
+
522
+ # Generic Go
523
+ else:
524
+ return {
525
+ 'type': 'go',
526
+ 'build_command': 'go build -o dist/',
527
+ 'output_dir': 'dist',
528
+ 'install_command': 'go mod download',
529
+ 'language': 'go',
530
+ 'go_version': '1.21'
531
+ }
532
+
533
+ # Priority 7: Rust projects
534
+ if 'Cargo.toml' in files:
535
+ return {
536
+ 'type': 'rust',
537
+ 'build_command': 'trunk build --release',
538
+ 'output_dir': 'dist',
539
+ 'install_command': 'cargo install trunk',
540
+ 'language': 'rust',
541
+ 'rust_version': 'stable'
542
+ }
543
+
544
+ # Priority 8: Java projects
545
+ if 'pom.xml' in files:
546
+ return {
547
+ 'type': 'maven',
548
+ 'build_command': './mvnw clean package',
549
+ 'output_dir': 'target/classes/static',
550
+ 'install_command': '',
551
+ 'language': 'java',
552
+ 'java_version': '17'
553
+ }
554
+
555
+ if 'build.gradle' in files or 'build.gradle.kts' in files:
556
+ return {
557
+ 'type': 'gradle',
558
+ 'build_command': './gradlew build',
559
+ 'output_dir': 'build/resources/main/static',
560
+ 'install_command': '',
561
+ 'language': 'java',
562
+ 'java_version': '17'
563
+ }
564
+
565
+ # Priority 9: Static HTML
566
+ if 'index.html' in files:
567
+ return {
568
+ 'type': 'static',
569
+ 'build_command': '',
570
+ 'output_dir': '.',
571
+ 'install_command': '',
572
+ 'language': 'html'
573
+ }
574
+
575
+ # Default: Static
576
+ return {
577
+ 'type': 'static',
578
+ 'build_command': '',
579
+ 'output_dir': '.',
580
+ 'install_command': '',
581
+ 'language': 'unknown'
582
+ }
583
+
584
+ def generate_workflow_yaml(self, project_config: Dict, ftp_server: str,
585
+ ftp_username: str, branch: str = 'main') -> str:
586
+ """Generate GitHub Actions workflow YAML for deployment with multi-language support"""
587
+
588
+ language = project_config.get('language', 'unknown')
589
+ project_type = project_config['type']
590
+
591
+ workflow = f"""name: Deploy to Celestine Hosting
592
+
593
+ on:
594
+ push:
595
+ branches: [ {branch} ]
596
+ workflow_dispatch:
597
+
598
+ jobs:
599
+ deploy:
600
+ runs-on: ubuntu-latest
601
+
602
+ steps:
603
+ - name: 📥 Checkout code
604
+ uses: actions/checkout@v4
605
+
606
+ """
607
+
608
+ # Language-specific setup
609
+ if language in ['javascript', 'typescript'] or project_config.get('node_version'):
610
+ node_version = project_config.get('node_version', '18')
611
+ workflow += f""" - name: 📦 Setup Node.js
612
+ uses: actions/setup-node@v4
613
+ with:
614
+ node-version: '{node_version}'
615
+ cache: 'npm'
616
+
617
+ """
618
+
619
+ elif language == 'python':
620
+ python_version = project_config.get('python_version', '3.11')
621
+ workflow += f""" - name: 🐍 Setup Python
622
+ uses: actions/setup-python@v4
623
+ with:
624
+ python-version: '{python_version}'
625
+ cache: 'pip'
626
+
627
+ """
628
+
629
+ elif language == 'php':
630
+ php_version = project_config.get('php_version', '8.2')
631
+ workflow += f""" - name: 🐘 Setup PHP
632
+ uses: shivammathur/setup-php@v2
633
+ with:
634
+ php-version: '{php_version}'
635
+ tools: composer
636
+
637
+ """
638
+ # PHP projects might also need Node.js
639
+ if project_config.get('node_version'):
640
+ workflow += f""" - name: 📦 Setup Node.js
641
+ uses: actions/setup-node@v4
642
+ with:
643
+ node-version: '{project_config.get('node_version', '18')}'
644
+ cache: 'npm'
645
+
646
+ """
647
+
648
+ elif language == 'ruby':
649
+ ruby_version = project_config.get('ruby_version', '3.2')
650
+ workflow += f""" - name: 💎 Setup Ruby
651
+ uses: ruby/setup-ruby@v1
652
+ with:
653
+ ruby-version: '{ruby_version}'
654
+ bundler-cache: true
655
+
656
+ """
657
+
658
+ elif language == 'go' or project_type == 'hugo':
659
+ if project_type == 'hugo':
660
+ hugo_version = project_config.get('hugo_version', 'latest')
661
+ workflow += f""" - name: 🚀 Setup Hugo
662
+ uses: peaceiris/actions-hugo@v2
663
+ with:
664
+ hugo-version: '{hugo_version}'
665
+ extended: true
666
+
667
+ """
668
+ else:
669
+ go_version = project_config.get('go_version', '1.21')
670
+ workflow += f""" - name: 🔷 Setup Go
671
+ uses: actions/setup-go@v4
672
+ with:
673
+ go-version: '{go_version}'
674
+
675
+ """
676
+
677
+ elif language == 'rust':
678
+ workflow += f""" - name: 🦀 Setup Rust
679
+ uses: actions-rs/toolchain@v1
680
+ with:
681
+ toolchain: stable
682
+ override: true
683
+
684
+ - name: 📦 Install Trunk
685
+ run: cargo install trunk
686
+
687
+ """
688
+
689
+ elif language == 'java':
690
+ java_version = project_config.get('java_version', '17')
691
+ workflow += f""" - name: ☕ Setup Java
692
+ uses: actions/setup-java@v3
693
+ with:
694
+ java-version: '{java_version}'
695
+ distribution: 'temurin'
696
+
697
+ """
698
+
699
+ # Install dependencies
700
+ if project_config['install_command']:
701
+ workflow += f""" - name: 📚 Install dependencies
702
+ run: {project_config['install_command']}
703
+
704
+ """
705
+
706
+ # Build project
707
+ if project_config['build_command']:
708
+ workflow += f""" - name: 🔨 Build project
709
+ run: {project_config['build_command']}
710
+ env:
711
+ CI: false
712
+ NODE_ENV: production
713
+
714
+ """
715
+
716
+ # FTP deployment
717
+ workflow += f""" - name: 🚀 Deploy to VistaPanel via FTP
718
+ uses: SamKirkland/FTP-Deploy-Action@v4.3.4
719
+ with:
720
+ server: {ftp_server}
721
+ username: ${{{{ secrets.FTP_USERNAME }}}}
722
+ password: ${{{{ secrets.FTP_PASSWORD }}}}
723
+ local-dir: ./{project_config['output_dir']}/
724
+ server-dir: ./htdocs/
725
+ dangerous-clean-slate: false
726
+ exclude: |
727
+ **/.git*
728
+ **/.git*/**
729
+ **/node_modules/**
730
+ **/.env
731
+ **/.env.*
732
+ **/vendor/**
733
+ **/__pycache__/**
734
+ **/*.pyc
735
+ **/target/**
736
+ **/Cargo.lock
737
+
738
+ - name: ✅ Deployment complete
739
+ run: |
740
+ echo "🎉 Deployment successful!"
741
+ echo "📦 Project type: {project_type}"
742
+ echo "🔨 Build command: {project_config['build_command'] or 'None'}"
743
+ echo "📂 Output directory: {project_config['output_dir']}"
744
+ echo "🌐 Your site is live!"
745
+ """
746
+
747
+ return workflow
748
+
749
+ def inject_workflow(self, owner: str, repo: str, workflow_content: str,
750
+ access_token: str, branch: str = 'main') -> bool:
751
+ """Inject workflow file into repository"""
752
+ try:
753
+ headers = {
754
+ 'Authorization': f'token {access_token}',
755
+ 'Accept': 'application/vnd.github.v3+json'
756
+ }
757
+
758
+ # Check if .github/workflows directory exists
759
+ workflow_path = '.github/workflows/celestine_deploy.yml'
760
+
761
+ # Get file SHA if it exists (for updates)
762
+ sha = None
763
+ try:
764
+ response = requests.get(
765
+ f'{self.github_api}/repos/{owner}/{repo}/contents/{workflow_path}',
766
+ headers=headers,
767
+ params={'ref': branch},
768
+ timeout=30
769
+ )
770
+ if response.status_code == 200:
771
+ sha = response.json()['sha']
772
+ except:
773
+ pass
774
+
775
+ # Create or update file
776
+ payload = {
777
+ 'message': '🚀 Add Celestine Hosting deployment workflow',
778
+ 'content': base64.b64encode(workflow_content.encode()).decode(),
779
+ 'branch': branch
780
+ }
781
+
782
+ if sha:
783
+ payload['sha'] = sha
784
+
785
+ response = requests.put(
786
+ f'{self.github_api}/repos/{owner}/{repo}/contents/{workflow_path}',
787
+ headers=headers,
788
+ json=payload,
789
+ timeout=30
790
+ )
791
+
792
+ return response.status_code in [200, 201]
793
+ except Exception as e:
794
+ logger.error(f"Failed to inject workflow: {e}")
795
+ return False
796
+
797
+ def setup_deployment(self, owner: str, repo: str, access_token: str,
798
+ ftp_server: str, ftp_username: str, ftp_password: str,
799
+ branch: str = 'main') -> Dict:
800
+ """
801
+ Complete deployment setup:
802
+ 1. Detect project type
803
+ 2. Create FTP secrets
804
+ 3. Inject workflow file
805
+ """
806
+ try:
807
+ logger.info(f"Setting up deployment for {owner}/{repo}")
808
+
809
+ # Detect project type
810
+ logger.info("Detecting project type...")
811
+ project_config = self.detect_project_type(owner, repo, access_token)
812
+ logger.info(f"Detected: {project_config['type']}")
813
+
814
+ # Create secrets
815
+ logger.info("Creating FTP secrets...")
816
+ ftp_user_created = self.create_or_update_secret(
817
+ owner, repo, 'FTP_USERNAME', ftp_username, access_token
818
+ )
819
+ ftp_pass_created = self.create_or_update_secret(
820
+ owner, repo, 'FTP_PASSWORD', ftp_password, access_token
821
+ )
822
+
823
+ if not (ftp_user_created and ftp_pass_created):
824
+ raise Exception("Failed to create FTP secrets")
825
+
826
+ logger.info("Secrets created successfully")
827
+
828
+ # Generate workflow
829
+ logger.info("Generating workflow file...")
830
+ workflow_content = self.generate_workflow_yaml(
831
+ project_config, ftp_server, ftp_username, branch
832
+ )
833
+
834
+ # Inject workflow
835
+ logger.info("Injecting workflow into repository...")
836
+ workflow_injected = self.inject_workflow(
837
+ owner, repo, workflow_content, access_token, branch
838
+ )
839
+
840
+ if not workflow_injected:
841
+ raise Exception("Failed to inject workflow file")
842
+
843
+ logger.info("Workflow injected successfully")
844
+
845
+ return {
846
+ 'success': True,
847
+ 'project_type': project_config['type'],
848
+ 'build_command': project_config['build_command'],
849
+ 'output_dir': project_config['output_dir'],
850
+ 'workflow_url': f'https://github.com/{owner}/{repo}/blob/{branch}/.github/workflows/celestine_deploy.yml',
851
+ 'actions_url': f'https://github.com/{owner}/{repo}/actions'
852
+ }
853
+ except Exception as e:
854
+ logger.error(f"Deployment setup failed: {e}")
855
+ return {
856
+ 'success': False,
857
+ 'error': str(e)
858
+ }
859
+
860
+ def get_workflow_runs(self, owner: str, repo: str, access_token: str,
861
+ limit: int = 10) -> List[Dict]:
862
+ """Get workflow run history"""
863
+ try:
864
+ headers = {
865
+ 'Authorization': f'token {access_token}',
866
+ 'Accept': 'application/vnd.github.v3+json'
867
+ }
868
+
869
+ response = requests.get(
870
+ f'{self.github_api}/repos/{owner}/{repo}/actions/runs',
871
+ headers=headers,
872
+ params={'per_page': limit},
873
+ timeout=30
874
+ )
875
+
876
+ if response.status_code != 200:
877
+ return []
878
+
879
+ runs = response.json()['workflow_runs']
880
+
881
+ return [{
882
+ 'id': run['id'],
883
+ 'name': run['name'],
884
+ 'status': run['status'],
885
+ 'conclusion': run['conclusion'],
886
+ 'created_at': run['created_at'],
887
+ 'updated_at': run['updated_at'],
888
+ 'html_url': run['html_url'],
889
+ 'run_number': run['run_number']
890
+ } for run in runs]
891
+ except Exception as e:
892
+ logger.error(f"Failed to get workflow runs: {e}")
893
+ return []
894
+
895
+ def get_workflow_logs(self, owner: str, repo: str, run_id: int,
896
+ access_token: str) -> str:
897
+ """Get workflow run logs"""
898
+ try:
899
+ headers = {
900
+ 'Authorization': f'token {access_token}',
901
+ 'Accept': 'application/vnd.github.v3+json'
902
+ }
903
+
904
+ response = requests.get(
905
+ f'{self.github_api}/repos/{owner}/{repo}/actions/runs/{run_id}/logs',
906
+ headers=headers,
907
+ timeout=30,
908
+ allow_redirects=True
909
+ )
910
+
911
+ if response.status_code == 200:
912
+ return response.text
913
+ return ""
914
+ except Exception as e:
915
+ logger.error(f"Failed to get logs: {e}")
916
+ return ""
917
+
918
+ def trigger_workflow(self, owner: str, repo: str, workflow_file: str,
919
+ access_token: str, branch: str = 'main') -> bool:
920
+ """Manually trigger a workflow"""
921
+ try:
922
+ headers = {
923
+ 'Authorization': f'token {access_token}',
924
+ 'Accept': 'application/vnd.github.v3+json'
925
+ }
926
+
927
+ response = requests.post(
928
+ f'{self.github_api}/repos/{owner}/{repo}/actions/workflows/{workflow_file}/dispatches',
929
+ headers=headers,
930
+ json={'ref': branch},
931
+ timeout=30
932
+ )
933
+
934
+ return response.status_code == 204
935
+ except Exception as e:
936
+ logger.error(f"Failed to trigger workflow: {e}")
937
+ return False
hf-mofh-api.php CHANGED
@@ -1,129 +1,129 @@
1
- <?php
2
- /**
3
- * Hugging Face Space MOFH API Proxy Client
4
- * Bypasses ByetHost restrictions by using HF Space as proxy
5
- */
6
-
7
- class HF_MOFH_API
8
- {
9
- private $hf_api_url;
10
-
11
- public function __construct($hf_api_url)
12
- {
13
- $this->hf_api_url = rtrim($hf_api_url, '/');
14
- }
15
-
16
- /**
17
- * Create a new hosting account via HF Space
18
- */
19
- public function createAccount($username, $password, $email, $domain, $plan = 'free')
20
- {
21
- $data = [
22
- 'username' => $username,
23
- 'password' => $password,
24
- 'email' => $email,
25
- 'domain' => $domain,
26
- 'plan' => $plan
27
- ];
28
-
29
- return $this->makeRequest('/create-account', $data);
30
- }
31
-
32
- /**
33
- * Suspend an account
34
- */
35
- public function suspendAccount($username, $reason = 'Suspended by admin')
36
- {
37
- $data = [
38
- 'username' => $username,
39
- 'reason' => $reason
40
- ];
41
-
42
- return $this->makeRequest('/suspend-account', $data);
43
- }
44
-
45
- /**
46
- * Unsuspend an account
47
- */
48
- public function unsuspendAccount($username)
49
- {
50
- $data = [
51
- 'username' => $username
52
- ];
53
-
54
- return $this->makeRequest('/unsuspend-account', $data);
55
- }
56
-
57
- /**
58
- * Make API request to Hugging Face Space
59
- */
60
- private function makeRequest($endpoint, $data = [])
61
- {
62
- $url = $this->hf_api_url . $endpoint;
63
-
64
- $ch = curl_init($url);
65
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
66
- curl_setopt($ch, CURLOPT_POST, true);
67
- curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
68
- curl_setopt($ch, CURLOPT_HTTPHEADER, [
69
- 'Content-Type: application/json',
70
- 'User-Agent: Celestine-Hosting/1.0'
71
- ]);
72
- curl_setopt($ch, CURLOPT_TIMEOUT, 60);
73
- curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
74
- curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
75
- curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
76
-
77
- $response = curl_exec($ch);
78
- $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
79
- $error = curl_error($ch);
80
- curl_close($ch);
81
-
82
- if ($error) {
83
- return [
84
- 'success' => false,
85
- 'http_code' => $http_code,
86
- 'error' => $error,
87
- 'response' => null
88
- ];
89
- }
90
-
91
- $result = json_decode($response, true);
92
-
93
- if (!$result) {
94
- return [
95
- 'success' => false,
96
- 'http_code' => $http_code,
97
- 'error' => 'Invalid JSON response',
98
- 'response' => $response
99
- ];
100
- }
101
-
102
- return array_merge($result, [
103
- 'http_code' => $http_code
104
- ]);
105
- }
106
-
107
- /**
108
- * Test connection to HF Space
109
- */
110
- public function testConnection()
111
- {
112
- $ch = curl_init($this->hf_api_url . '/');
113
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
114
- curl_setopt($ch, CURLOPT_TIMEOUT, 10);
115
-
116
- $response = curl_exec($ch);
117
- $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
118
- $error = curl_error($ch);
119
- curl_close($ch);
120
-
121
- return [
122
- 'success' => ($http_code == 200 && !$error),
123
- 'http_code' => $http_code,
124
- 'error' => $error,
125
- 'response' => json_decode($response, true)
126
- ];
127
- }
128
- }
129
  ?>
 
1
+ <?php
2
+ /**
3
+ * Hugging Face Space MOFH API Proxy Client
4
+ * Bypasses ByetHost restrictions by using HF Space as proxy
5
+ */
6
+
7
+ class HF_MOFH_API
8
+ {
9
+ private $hf_api_url;
10
+
11
+ public function __construct($hf_api_url)
12
+ {
13
+ $this->hf_api_url = rtrim($hf_api_url, '/');
14
+ }
15
+
16
+ /**
17
+ * Create a new hosting account via HF Space
18
+ */
19
+ public function createAccount($username, $password, $email, $domain, $plan = 'free')
20
+ {
21
+ $data = [
22
+ 'username' => $username,
23
+ 'password' => $password,
24
+ 'email' => $email,
25
+ 'domain' => $domain,
26
+ 'plan' => $plan
27
+ ];
28
+
29
+ return $this->makeRequest('/create-account', $data);
30
+ }
31
+
32
+ /**
33
+ * Suspend an account
34
+ */
35
+ public function suspendAccount($username, $reason = 'Suspended by admin')
36
+ {
37
+ $data = [
38
+ 'username' => $username,
39
+ 'reason' => $reason
40
+ ];
41
+
42
+ return $this->makeRequest('/suspend-account', $data);
43
+ }
44
+
45
+ /**
46
+ * Unsuspend an account
47
+ */
48
+ public function unsuspendAccount($username)
49
+ {
50
+ $data = [
51
+ 'username' => $username
52
+ ];
53
+
54
+ return $this->makeRequest('/unsuspend-account', $data);
55
+ }
56
+
57
+ /**
58
+ * Make API request to Hugging Face Space
59
+ */
60
+ private function makeRequest($endpoint, $data = [])
61
+ {
62
+ $url = $this->hf_api_url . $endpoint;
63
+
64
+ $ch = curl_init($url);
65
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
66
+ curl_setopt($ch, CURLOPT_POST, true);
67
+ curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
68
+ curl_setopt($ch, CURLOPT_HTTPHEADER, [
69
+ 'Content-Type: application/json',
70
+ 'User-Agent: Celestine-Hosting/1.0'
71
+ ]);
72
+ curl_setopt($ch, CURLOPT_TIMEOUT, 60);
73
+ curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
74
+ curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
75
+ curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
76
+
77
+ $response = curl_exec($ch);
78
+ $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
79
+ $error = curl_error($ch);
80
+ curl_close($ch);
81
+
82
+ if ($error) {
83
+ return [
84
+ 'success' => false,
85
+ 'http_code' => $http_code,
86
+ 'error' => $error,
87
+ 'response' => null
88
+ ];
89
+ }
90
+
91
+ $result = json_decode($response, true);
92
+
93
+ if (!$result) {
94
+ return [
95
+ 'success' => false,
96
+ 'http_code' => $http_code,
97
+ 'error' => 'Invalid JSON response',
98
+ 'response' => $response
99
+ ];
100
+ }
101
+
102
+ return array_merge($result, [
103
+ 'http_code' => $http_code
104
+ ]);
105
+ }
106
+
107
+ /**
108
+ * Test connection to HF Space
109
+ */
110
+ public function testConnection()
111
+ {
112
+ $ch = curl_init($this->hf_api_url . '/');
113
+ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
114
+ curl_setopt($ch, CURLOPT_TIMEOUT, 10);
115
+
116
+ $response = curl_exec($ch);
117
+ $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
118
+ $error = curl_error($ch);
119
+ curl_close($ch);
120
+
121
+ return [
122
+ 'success' => ($http_code == 200 && !$error),
123
+ 'http_code' => $http_code,
124
+ 'error' => $error,
125
+ 'response' => json_decode($response, true)
126
+ ];
127
+ }
128
+ }
129
  ?>
requirements.txt CHANGED
@@ -1,5 +1,8 @@
1
- fastapi>=0.104.1
2
- uvicorn[standard]>=0.24.0
3
- pydantic>=2.5.0
4
- requests>=2.31.0
5
- psutil>=5.9.6
 
 
 
 
1
+ fastapi>=0.104.1
2
+ uvicorn[standard]>=0.24.0
3
+ pydantic>=2.5.0
4
+ requests>=2.31.0
5
+ psutil>=5.9.6
6
+ PyJWT>=2.8.0
7
+ PyNaCl>=1.5.0
8
+ cryptography>=41.0.0