NitinBot002 commited on
Commit
83e6f13
·
verified ·
1 Parent(s): f90ad11

Upload 3 files

Browse files
Files changed (3) hide show
  1. Dockerfile +35 -0
  2. app.py +217 -0
  3. requirements.txt +2 -0
Dockerfile ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dockerfile
2
+ FROM python:3.9-slim
3
+
4
+ # Install system dependencies
5
+ RUN apt-get update && apt-get install -y \
6
+ curl \
7
+ wget \
8
+ git \
9
+ build-essential \
10
+ nodejs \
11
+ npm \
12
+ && rm -rf /var/lib/apt/lists/*
13
+
14
+ # Set working directory
15
+ WORKDIR /app
16
+
17
+ # Copy requirements and install Python packages
18
+ COPY requirements.txt .
19
+ RUN pip install --no-cache-dir -r requirements.txt
20
+
21
+ # Copy application files
22
+ COPY . .
23
+
24
+ # Create workspace directory
25
+ RUN mkdir -p /tmp/workspace
26
+
27
+ # Expose ports
28
+ EXPOSE 7860 8080
29
+
30
+ # Set environment variables
31
+ ENV PORT=7860
32
+ ENV CODE_SERVER_PASSWORD=huggingface123
33
+
34
+ # Run the application
35
+ CMD ["python", "app.py"]
app.py ADDED
@@ -0,0 +1,217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # app.py - Main application file
2
+ import os
3
+ import subprocess
4
+ import threading
5
+ import time
6
+ from flask import Flask, jsonify, redirect
7
+ import signal
8
+ import sys
9
+
10
+ app = Flask(__name__)
11
+
12
+ # Global variable to track code-server process
13
+ code_server_process = None
14
+
15
+ def install_code_server():
16
+ """Install code-server"""
17
+ try:
18
+ print("Installing code-server...")
19
+ # Download and install code-server
20
+ subprocess.run([
21
+ "curl", "-fsSL", "https://code-server.dev/install.sh"
22
+ ], check=True, capture_output=True, text=True)
23
+
24
+ # Make it executable and install
25
+ install_cmd = "curl -fsSL https://code-server.dev/install.sh | sh"
26
+ subprocess.run(install_cmd, shell=True, check=True)
27
+
28
+ print("Code-server installed successfully!")
29
+ return True
30
+ except subprocess.CalledProcessError as e:
31
+ print(f"Error installing code-server: {e}")
32
+ return False
33
+
34
+ def start_code_server():
35
+ """Start code-server in background"""
36
+ global code_server_process
37
+ try:
38
+ # Create config directory
39
+ config_dir = os.path.expanduser("~/.config/code-server")
40
+ os.makedirs(config_dir, exist_ok=True)
41
+
42
+ # Set password (you can change this)
43
+ password = os.getenv("CODE_SERVER_PASSWORD", "huggingface123")
44
+
45
+ # Start code-server
46
+ cmd = [
47
+ "code-server",
48
+ "--bind-addr", "0.0.0.0:8080",
49
+ "--auth", "password",
50
+ "--password", password,
51
+ "--disable-telemetry",
52
+ "--disable-update-check"
53
+ ]
54
+
55
+ print("Starting code-server...")
56
+ code_server_process = subprocess.Popen(
57
+ cmd,
58
+ stdout=subprocess.PIPE,
59
+ stderr=subprocess.PIPE,
60
+ text=True
61
+ )
62
+
63
+ # Wait a bit for it to start
64
+ time.sleep(5)
65
+
66
+ if code_server_process.poll() is None:
67
+ print("Code-server started successfully!")
68
+ print(f"Password: {password}")
69
+ return True
70
+ else:
71
+ print("Code-server failed to start")
72
+ return False
73
+
74
+ except Exception as e:
75
+ print(f"Error starting code-server: {e}")
76
+ return False
77
+
78
+ def setup_workspace():
79
+ """Setup initial workspace"""
80
+ try:
81
+ # Create workspace directory
82
+ workspace_dir = "/tmp/workspace"
83
+ os.makedirs(workspace_dir, exist_ok=True)
84
+
85
+ # Create a sample file
86
+ sample_file = os.path.join(workspace_dir, "README.md")
87
+ with open(sample_file, "w") as f:
88
+ f.write("""# Code-Server on Hugging Face Spaces
89
+
90
+ Welcome to your code-server environment!
91
+
92
+ ## Features:
93
+ - Full VS Code experience in browser
94
+ - Python environment ready
95
+ - Terminal access
96
+ - File editing capabilities
97
+
98
+ ## Getting Started:
99
+ 1. Open terminal (Ctrl+Shift+`)
100
+ 2. Install packages: `pip install package-name`
101
+ 3. Start coding!
102
+
103
+ ## Note:
104
+ - Files are temporary and will be lost on restart
105
+ - For persistent storage, use external git repos
106
+ """)
107
+
108
+ # Create sample Python file
109
+ sample_py = os.path.join(workspace_dir, "sample.py")
110
+ with open(sample_py, "w") as f:
111
+ f.write("""#!/usr/bin/env python3
112
+ # Sample Python file
113
+
114
+ def hello_world():
115
+ print("Hello from Code-Server on Hugging Face!")
116
+
117
+ if __name__ == "__main__":
118
+ hello_world()
119
+ """)
120
+
121
+ print("Workspace setup complete!")
122
+ return True
123
+
124
+ except Exception as e:
125
+ print(f"Error setting up workspace: {e}")
126
+ return False
127
+
128
+ @app.route('/health')
129
+ def health_check():
130
+ """Health check endpoint"""
131
+ global code_server_process
132
+
133
+ status = {
134
+ "status": "healthy",
135
+ "timestamp": time.time(),
136
+ "code_server_running": False
137
+ }
138
+
139
+ if code_server_process:
140
+ if code_server_process.poll() is None:
141
+ status["code_server_running"] = True
142
+ else:
143
+ status["code_server_running"] = False
144
+ status["status"] = "code_server_down"
145
+
146
+ return jsonify(status)
147
+
148
+ @app.route('/')
149
+ def index():
150
+ """Redirect to code-server"""
151
+ return redirect('/code-server/', code=302)
152
+
153
+ @app.route('/code-server/')
154
+ def code_server_proxy():
155
+ """Info about code-server access"""
156
+ return """
157
+ <html>
158
+ <head><title>Code-Server Access</title></head>
159
+ <body>
160
+ <h1>Code-Server on Hugging Face Spaces</h1>
161
+ <p>Code-server should be running on port 8080</p>
162
+ <p>If you're seeing this, the proxy might not be working correctly.</p>
163
+ <p>Try accessing directly through the Hugging Face Spaces interface.</p>
164
+ <p><a href="/health">Check Health Status</a></p>
165
+ </body>
166
+ </html>
167
+ """
168
+
169
+ def signal_handler(sig, frame):
170
+ """Handle shutdown gracefully"""
171
+ global code_server_process
172
+ print("Shutting down...")
173
+
174
+ if code_server_process:
175
+ code_server_process.terminate()
176
+ code_server_process.wait()
177
+
178
+ sys.exit(0)
179
+
180
+ def initialize_environment():
181
+ """Initialize the complete environment"""
182
+ print("Initializing environment...")
183
+
184
+ # Install code-server
185
+ if not install_code_server():
186
+ print("Failed to install code-server")
187
+ return False
188
+
189
+ # Setup workspace
190
+ if not setup_workspace():
191
+ print("Failed to setup workspace")
192
+ return False
193
+
194
+ # Start code-server in background thread
195
+ def start_server():
196
+ start_code_server()
197
+
198
+ server_thread = threading.Thread(target=start_server, daemon=True)
199
+ server_thread.start()
200
+
201
+ return True
202
+
203
+ if __name__ == "__main__":
204
+ # Register signal handlers
205
+ signal.signal(signal.SIGINT, signal_handler)
206
+ signal.signal(signal.SIGTERM, signal_handler)
207
+
208
+ # Initialize environment
209
+ if initialize_environment():
210
+ print("Environment initialized successfully!")
211
+
212
+ # Start Flask app
213
+ port = int(os.getenv("PORT", 7860))
214
+ app.run(host="0.0.0.0", port=port, debug=False)
215
+ else:
216
+ print("Failed to initialize environment")
217
+ sys.exit(1)
requirements.txt ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ flask==2.3.3
2
+ requests==2.31.0