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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import os
|
2 |
+
import time
|
3 |
+
import subprocess
|
4 |
+
import requests
|
5 |
+
import traceback
|
6 |
+
import gradio as gr
|
7 |
+
|
8 |
+
# Node-related files configuration
|
9 |
+
MAIN_FILES = {
|
10 |
+
'.env': """HF_API_TOKEN=YOUR_HF_API_TOKEN_HERE
|
11 |
+
NODE_ENV=production
|
12 |
+
PORT=3000
|
13 |
+
RATE_LIMIT_WINDOW_MS=60000
|
14 |
+
RATE_LIMIT_MAX=100
|
15 |
+
HF_API_URL=https://api-inference.huggingface.co/models/distilbert-base-uncased-finetuned-sst-2-english
|
16 |
+
""",
|
17 |
+
|
18 |
+
'package.json': """{
|
19 |
+
"name": "compassionate-community",
|
20 |
+
"version": "1.0.0",
|
21 |
+
"description": "A sentiment-based story ordering web app",
|
22 |
+
"main": "server.js",
|
23 |
+
"scripts": {
|
24 |
+
"start": "node server.js"
|
25 |
+
},
|
26 |
+
"dependencies": {
|
27 |
+
"cors": "^2.8.5",
|
28 |
+
"dotenv": "^16.0.3",
|
29 |
+
"express": "^4.18.2",
|
30 |
+
"helmet": "^6.0.1",
|
31 |
+
"node-fetch": "^3.3.1",
|
32 |
+
"pino": "^8.5.0",
|
33 |
+
"pino-pretty": "^10.0.0",
|
34 |
+
"express-rate-limit": "^6.7.0"
|
35 |
+
},
|
36 |
+
"engines": {
|
37 |
+
"node": ">=16.0.0"
|
38 |
+
}
|
39 |
+
}
|
40 |
+
""",
|
41 |
+
|
42 |
+
'server.js': """const express = require('express');
|
43 |
+
const helmet = require('helmet');
|
44 |
+
const cors = require('cors');
|
45 |
+
const rateLimit = require('express-rate-limit');
|
46 |
+
const { port, nodeEnv, rateLimitWindowMs, rateLimitMax } = require('./config');
|
47 |
+
const sentimentRoutes = require('./routes/sentiment');
|
48 |
+
const logger = require('./logger');
|
49 |
+
|
50 |
+
const app = express();
|
51 |
+
|
52 |
+
app.use(helmet());
|
53 |
+
app.use(cors());
|
54 |
+
app.use(express.json());
|
55 |
+
|
56 |
+
const limiter = rateLimit({
|
57 |
+
windowMs: rateLimitWindowMs,
|
58 |
+
max: rateLimitMax,
|
59 |
+
message: { error: 'Too many requests, please try again later' }
|
60 |
+
});
|
61 |
+
|
62 |
+
app.use(limiter);
|
63 |
+
|
64 |
+
app.use('/sentiment', sentimentRoutes);
|
65 |
+
app.use(express.static('public'));
|
66 |
+
|
67 |
+
app.use((req,res)=>{
|
68 |
+
res.status(404).json({error:'Not Found'});
|
69 |
+
});
|
70 |
+
|
71 |
+
app.use((err,req,res,next)=>{
|
72 |
+
logger.error({ err }, 'Unhandled error');
|
73 |
+
res.status(500).json({error:'Internal Server Error'});
|
74 |
+
});
|
75 |
+
|
76 |
+
app.listen(port, () => {
|
77 |
+
logger.info(`Server running on http://localhost:${port} in ${nodeEnv} mode`);
|
78 |
+
});
|
79 |
+
""",
|
80 |
+
|
81 |
+
'config.js': """require('dotenv').config();
|
82 |
+
|
83 |
+
const requiredVars = ['HF_API_TOKEN', 'HF_API_URL', 'PORT', 'RATE_LIMIT_WINDOW_MS', 'RATE_LIMIT_MAX'];
|
84 |
+
requiredVars.forEach(v => {
|
85 |
+
if (!process.env[v]) {
|
86 |
+
console.error(`ERROR: Missing required environment variable ${v}`);
|
87 |
+
process.exit(1);
|
88 |
+
}
|
89 |
+
});
|
90 |
+
|
91 |
+
module.exports = {
|
92 |
+
hfApiToken: process.env.HF_API_TOKEN,
|
93 |
+
hfApiUrl: process.env.HF_API_URL,
|
94 |
+
port: process.env.PORT,
|
95 |
+
rateLimitWindowMs: parseInt(process.env.RATE_LIMIT_WINDOW_MS, 10),
|
96 |
+
rateLimitMax: parseInt(process.env.RATE_LIMIT_MAX, 10),
|
97 |
+
nodeEnv: process.env.NODE_ENV || 'development'
|
98 |
+
};
|
99 |
+
""",
|
100 |
+
|
101 |
+
'logger.js': """const pino = require('pino');
|
102 |
+
module.exports = pino({
|
103 |
+
level: process.env.NODE_ENV === 'production' ? 'info' : 'debug',
|
104 |
+
transport: process.env.NODE_ENV !== 'production' ? {
|
105 |
+
target: 'pino-pretty',
|
106 |
+
options: { colorize: true }
|
107 |
+
} : undefined
|
108 |
+
});
|
109 |
+
""",
|
110 |
+
|
111 |
+
'routes/sentiment.js': """const express = require('express');
|
112 |
+
const router = express.Router();
|
113 |
+
const { getSentiment } = require('../utils/huggingface');
|
114 |
+
const logger = require('../logger');
|
115 |
+
|
116 |
+
router.post('/', async (req, res) => {
|
117 |
+
const { text } = req.body;
|
118 |
+
if (!text) {
|
119 |
+
return res.status(400).json({ error: 'No text provided' });
|
120 |
+
}
|
121 |
+
|
122 |
+
try {
|
123 |
+
const sentiment = await getSentiment(text);
|
124 |
+
return res.json({ sentiment });
|
125 |
+
} catch (err) {
|
126 |
+
logger.error({ err }, 'Error fetching sentiment');
|
127 |
+
return res.status(500).json({ error: 'Internal server error' });
|
128 |
+
}
|
129 |
+
});
|
130 |
+
|
131 |
+
module.exports = router;
|
132 |
+
""",
|
133 |
+
|
134 |
+
'utils/huggingface.js': """const fetch = require('node-fetch');
|
135 |
+
const { hfApiToken, hfApiUrl } = require('../config');
|
136 |
+
const logger = require('../logger');
|
137 |
+
|
138 |
+
async function getSentiment(text) {
|
139 |
+
const response = await fetch(hfApiUrl, {
|
140 |
+
method: 'POST',
|
141 |
+
headers: {
|
142 |
+
'Authorization': `Bearer ${hfApiToken}`,
|
143 |
+
'Content-Type': 'application/json'
|
144 |
+
},
|
145 |
+
body: JSON.stringify({ inputs: text })
|
146 |
+
});
|
147 |
+
|
148 |
+
if (!response.ok) {
|
149 |
+
logger.error(`Hugging Face API error: ${response.status} - ${response.statusText}`);
|
150 |
+
throw new Error(`HF API request failed with status ${response.status}`);
|
151 |
+
}
|
152 |
+
|
153 |
+
const data = await response.json();
|
154 |
+
if (!Array.isArray(data) || !data[0]) {
|
155 |
+
throw new Error('Unexpected HF API response format');
|
156 |
+
}
|
157 |
+
|
158 |
+
const { label, score } = data[0];
|
159 |
+
return label === 'NEGATIVE' ? 1 - score : score;
|
160 |
+
}
|
161 |
+
|
162 |
+
module.exports = { getSentiment };
|
163 |
+
""",
|
164 |
+
|
165 |
+
'Dockerfile': """FROM node:18-alpine
|
166 |
+
WORKDIR /app
|
167 |
+
COPY package*.json ./
|
168 |
+
RUN npm install --production
|
169 |
+
COPY . .
|
170 |
+
EXPOSE 3000
|
171 |
+
CMD ["npm", "start"]
|
172 |
+
""",
|
173 |
+
|
174 |
+
'README.md': """# Compassionate Community
|
175 |
+
|
176 |
+
A sentiment-based web service using Hugging Face. Add your HF token to .env or as a Space secret and run npm install & npm start.
|
177 |
+
"""
|
178 |
+
}
|
179 |
+
|
180 |
+
PUBLIC_FILES = {
|
181 |
+
'index.html': """<!DOCTYPE html>
|
182 |
+
<html lang="en">
|
183 |
+
<head>
|
184 |
+
<meta charset="UTF-8"/>
|
185 |
+
<meta name="viewport" content="width=device-width,initial-scale=1.0"/>
|
186 |
+
<title>Compassionate Community</title>
|
187 |
+
<link rel="stylesheet" href="style.css"/>
|
188 |
+
</head>
|
189 |
+
<body>
|
190 |
+
<h1>Compassionate Community</h1>
|
191 |
+
<p>This page served by Node.js backend. For demonstration, use the Gradio interface to query sentiment.</p>
|
192 |
+
</body>
|
193 |
+
</html>
|
194 |
+
""",
|
195 |
+
|
196 |
+
'style.css': """body {
|
197 |
+
font-family: Arial, sans-serif;
|
198 |
+
margin: 20px;
|
199 |
+
background: #f7f7f7;
|
200 |
+
}
|
201 |
+
|
202 |
+
h1 {
|
203 |
+
font-size: 24px;
|
204 |
+
margin-bottom: 10px;
|
205 |
+
}
|
206 |
+
"""
|
207 |
+
}
|
208 |
+
|
209 |
+
|
210 |
+
def create_project_files():
|
211 |
+
logs = []
|
212 |
+
base_dir = "compassionate-community"
|
213 |
+
try:
|
214 |
+
# If Hugging Face secret HF_API_TOKEN is available, use it
|
215 |
+
hf_api_token = os.getenv("HF_API_TOKEN", None)
|
216 |
+
|
217 |
+
if not os.path.exists(base_dir):
|
218 |
+
os.makedirs(base_dir)
|
219 |
+
logs.append(f"Created directory: {base_dir}")
|
220 |
+
|
221 |
+
# Write main files
|
222 |
+
for fname, content in MAIN_FILES.items():
|
223 |
+
fpath = os.path.join(base_dir, fname)
|
224 |
+
if not os.path.exists(fpath):
|
225 |
+
# If we have a token from the environment, inject it
|
226 |
+
if fname == '.env' and hf_api_token:
|
227 |
+
content = content.replace("YOUR_HF_API_TOKEN_HERE", hf_api_token)
|
228 |
+
with open(fpath, 'w', encoding='utf-8') as f:
|
229 |
+
f.write(content)
|
230 |
+
logs.append(f"Created file: {fpath}")
|
231 |
+
|
232 |
+
public_dir = os.path.join(base_dir, "public")
|
233 |
+
if not os.path.exists(public_dir):
|
234 |
+
os.makedirs(public_dir)
|
235 |
+
logs.append(f"Created directory: {public_dir}")
|
236 |
+
|
237 |
+
for fname, content in PUBLIC_FILES.items():
|
238 |
+
fpath = os.path.join(public_dir, fname)
|
239 |
+
if not os.path.exists(fpath):
|
240 |
+
with open(fpath, 'w', encoding='utf-8') as f:
|
241 |
+
f.write(content)
|
242 |
+
logs.append(f"Created file: {fpath}")
|
243 |
+
|
244 |
+
logs.append("Project structure set up successfully!")
|
245 |
+
except Exception as e:
|
246 |
+
logs.append("ERROR during setup:")
|
247 |
+
logs.append(str(e))
|
248 |
+
logs.append(traceback.format_exc())
|
249 |
+
return "\n".join(logs)
|
250 |
+
|
251 |
+
|
252 |
+
def start_node_server():
|
253 |
+
base_dir = "compassionate-community"
|
254 |
+
try:
|
255 |
+
# Install dependencies
|
256 |
+
subprocess.check_call(["npm", "install"], cwd=base_dir)
|
257 |
+
except Exception as e:
|
258 |
+
return f"Failed npm install: {e}"
|
259 |
+
|
260 |
+
# Start the server in the background
|
261 |
+
subprocess.Popen(["npm", "start"], cwd=base_dir)
|
262 |
+
|
263 |
+
# Wait for server to come up
|
264 |
+
for i in range(30):
|
265 |
+
try:
|
266 |
+
r = requests.get("http://localhost:3000")
|
267 |
+
if r.status_code in (200, 404):
|
268 |
+
return "Node server running at http://localhost:3000"
|
269 |
+
except:
|
270 |
+
pass
|
271 |
+
time.sleep(1)
|
272 |
+
|
273 |
+
return "Node server did not start within 30 seconds."
|
274 |
+
|
275 |
+
|
276 |
+
def get_sentiment(text):
|
277 |
+
url = "http://localhost:3000/sentiment"
|
278 |
+
try:
|
279 |
+
r = requests.post(url, json={"text": text}, timeout=10)
|
280 |
+
if r.status_code == 200:
|
281 |
+
data = r.json()
|
282 |
+
return f"Sentiment score: {data['sentiment']:.2f}"
|
283 |
+
else:
|
284 |
+
return f"Error: {r.status_code} {r.text}"
|
285 |
+
except Exception as e:
|
286 |
+
return f"Request failed: {e}"
|
287 |
+
|
288 |
+
|
289 |
+
# On startup, create files and start the server
|
290 |
+
setup_logs = create_project_files()
|
291 |
+
server_logs = start_node_server()
|
292 |
+
|
293 |
+
def query_interface(input_text):
|
294 |
+
# Check if token not replaced
|
295 |
+
with open("compassionate-community/.env", 'r', encoding='utf-8') as envf:
|
296 |
+
env_content = envf.read()
|
297 |
+
if "YOUR_HF_API_TOKEN_HERE" in env_content:
|
298 |
+
warning = "Warning: HF API Token not set. Please set a token and restart."
|
299 |
+
else:
|
300 |
+
warning = ""
|
301 |
+
sentiment_result = get_sentiment(input_text)
|
302 |
+
return f"{warning}\n{sentiment_result}"
|
303 |
+
|
304 |
+
with gr.Blocks() as demo:
|
305 |
+
gr.Markdown("# Compassionate Community Full Service\n")
|
306 |
+
gr.Markdown("**Setup Logs:**")
|
307 |
+
gr.Textbox(value=setup_logs, label="Setup Logs", interactive=False)
|
308 |
+
gr.Markdown("**Server Status:**")
|
309 |
+
gr.Textbox(value=server_logs, label="Server Status", interactive=False)
|
310 |
+
gr.Markdown("**Test the Sentiment Service:**")
|
311 |
+
input_text = gr.Textbox(placeholder="Enter text describing a struggle...")
|
312 |
+
output = gr.Textbox(label="Output")
|
313 |
+
run_button = gr.Button("Analyze Sentiment")
|
314 |
+
run_button.click(query_interface, inputs=input_text, outputs=output)
|
315 |
+
|
316 |
+
demo.launch(server_name="0.0.0.0", server_port=7860)
|