File size: 2,787 Bytes
d10c686 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 |
// @ts-nocheck
import express from 'express';
import cors from 'cors';
import multer from 'multer';
import { uploadFile } from '@huggingface/hub';
import path from 'path';
import { fileURLToPath } from 'url';
import dotenv from 'dotenv';
dotenv.config()
// Fix __dirname for ES Modules
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const app = express();
// Hugging Face Spaces requires port 7860
const port = process.env.PORT || 7860;
// Middleware
app.use(cors());
app.use(express.json());
// Configure Multer for memory storage (file buffer)
const storage = multer.memoryStorage();
const upload = multer({ storage: storage });
// SERVER CONFIGURATION
// PRIORITY: Environment Variable > Hardcoded Fallback
const SERVER_CONFIG = {
TOKEN: process.env.HF_TOKEN || '',
REPO: process.env.HF_REPO || 'TwanAPI/DataTwan',
TYPE: 'dataset'
};
// --- API ROUTES ---
// Upload Endpoint
app.post('/api/upload', upload.single('file'), async (req, res) => {
try {
const file = req.file;
const filePath = req.body.path;
if (!file) {
return res.status(400).json({ error: 'No file provided' });
}
if (!filePath) {
return res.status(400).json({ error: 'No file path provided' });
}
console.log(`[SERVER] Uploading: ${filePath} (${file.size} bytes)`);
// Upload to Hugging Face
const response = await uploadFile({
credentials: {
accessToken: SERVER_CONFIG.TOKEN,
},
repo: {
type: SERVER_CONFIG.TYPE,
name: SERVER_CONFIG.REPO
},
file: {
path: filePath,
content: new Blob([file.buffer]),
},
});
const commitHash = response.commit.oid;
const urlPrefix = "https://huggingface.co/datasets";
const publicUrl = `${urlPrefix}/${SERVER_CONFIG.REPO}/blob/${commitHash}/${filePath}`;
console.log(`[SERVER] Success: ${publicUrl}`);
res.json({
success: true,
url: publicUrl
});
} catch (error) {
console.error('[SERVER] Upload Error:', error);
res.status(500).json({
success: false,
error: error.message || 'Internal Server Error'
});
}
});
// --- SERVE FRONTEND (Production) ---
// Serve static files from the React build directory
app.use(express.static(path.join(__dirname, 'dist')));
// Handle React Routing (SPA) - Return index.html for any unknown route
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
// Start Server
app.listen(port, () => {
console.log(`--------------------------------------------------`);
console.log(`✅ Server running on port ${port}`);
console.log(` Target Repo: ${SERVER_CONFIG.REPO}`);
console.log(`--------------------------------------------------`);
}); |