uploadv2 / server.js
Twan07's picture
Create server.js
d10c686 verified
raw
history blame
2.79 kB
// @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(`--------------------------------------------------`);
});