Spaces:
Sleeping

File size: 4,633 Bytes
3560d2a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
104
105
106
107
108
109
110
111
112
113
114
115
116
const express = require('express');
const cors = require('cors');
const duckdb = require('duckdb');
const https = require('https');

const app = express();
app.use(cors());
const port = process.env.PORT || 3000;

// Tokens from environment variables for security
const HF_TOKEN = process.env.HF_TOKEN;
const HF_TOKEN_2 = process.env.HF_TOKEN_2 || HF_TOKEN; // Fallback to first token if not set
const db = new duckdb.Database(':memory:');

// In-Memory RAM Caching for Hugging Face S3 Links (30 minutes expiry) to maximize speed!
const linkCache = new Map();
const CACHE_TTL = 30 * 60 * 1000; 

async function getDirectLink(url, token = HF_TOKEN) {
    const cached = linkCache.get(url);
    if (cached && (Date.now() - cached.timestamp < CACHE_TTL)) {
        return cached.directLink;
    }

    return new Promise((resolve, reject) => {
        const options = { headers: { 'Authorization': `Bearer ${token}` }, method: 'HEAD' };
        const req = https.request(url, options, (res) => {
            if (res.statusCode === 302 || res.statusCode === 301) {
                const directLink = res.headers.location;
                linkCache.set(url, { directLink, timestamp: Date.now() });
                resolve(directLink);
            } else {
                reject(new Error(`Hugging Face error: ${res.statusCode}`));
            }
        });
        req.on('error', reject);
        req.end();
    });
}

// Database Initialization
async function initDB() {
    console.log("Initializing Cloud Search Engine (RAM Limit: 256MB)...");
    return new Promise((resolve, reject) => {
        db.run("INSTALL httpfs; LOAD httpfs;", (err) => {
            if (err) return reject(err);
            
            // CRITICAL: Limit memory usage for Render Free Tier (512MB total)
            db.run("PRAGMA max_memory='256MB';");
            db.run("PRAGMA memory_limit='256MB';");
            resolve();
        });
    });
}

const BASE_URL_1 = process.env.BASE_URL_1 || 'https://huggingface.co/datasets/digiintel/digiintell/resolve/main';
const BASE_URL_2 = process.env.BASE_URL_2 || 'https://huggingface.co/datasets/suraj14921/digiintel2/resolve/main';

const MOBILE_FILES = [
    ...Array.from({length: 10}, (_, i) => ({ url: `${BASE_URL_1}/hitek_mobile_part${i+1}.parquet`, token: HF_TOKEN })), // Batch 1 Mobile in Repo 1
    ...Array.from({length: 10}, (_, i) => ({ url: `${BASE_URL_2}/hitek2_mobile_part${i+1}.parquet`, token: HF_TOKEN_2 })) // Batch 2 Mobile in Repo 2
];

const ID_FILES = [
    ...Array.from({length: 10}, (_, i) => ({ url: `${BASE_URL_1}/hitek_id_part${i+1}.parquet`, token: HF_TOKEN })), // Batch 1 ID in Repo 1
    ...Array.from({length: 10}, (_, i) => ({ url: `${BASE_URL_1}/hitek2_id_part${i+1}.parquet`, token: HF_TOKEN })) // Batch 2 ID in Repo 1
];

// MOBILE SEARCH API
app.get('/search/mobile/:number', async (req, res) => {
    const number = req.params.number;
    console.log(`Mobile Search Request: ${number}`);
    
    try {
        const directLinks = await Promise.all(MOBILE_FILES.map(f => getDirectLink(f.url, f.token)));
        // Using 'mobile' column for number search
        const sql = `SELECT * FROM read_parquet([${directLinks.map(f => `'${f}'`).join(',')}], union_by_name=True) WHERE mobile = '${number}' LIMIT 10;`;
        
        db.all(sql, (err, rows) => {
            if (err) return res.status(500).json({ error: err.message });
            res.json({ results: rows, count: rows.length });
        });
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
});

// ID / AADHAR SEARCH API
app.get('/search/id/:id', async (req, res) => {
    const id = req.params.id;
    console.log(`Deep Aadhar Search Request: ${id}`);
    
    try {
        // FAST SEARCH: Only look in ID_FILES for Aadhar searches
        const directLinks = await Promise.all(ID_FILES.map(f => getDirectLink(f.url, f.token)));
        
        // Use 'id' column as confirmed by the database error message
        const sql = `SELECT * FROM read_parquet([${directLinks.map(f => `'${f}'`).join(',')}], union_by_name=True) 
                     WHERE id = '${id}' 
                     LIMIT 20;`;
        
        db.all(sql, (err, rows) => {
            if (err) return res.status(500).json({ error: err.message });
            res.json({ results: rows, count: rows.length });
        });
    } catch (e) {
        res.status(500).json({ error: e.message });
    }
});

app.get('/', (req, res) => res.send('Hi-Tek OSINT API is ONLINE 🚀'));

initDB().then(() => {
    app.listen(port, () => console.log(`🚀 API Server running at port ${port}`));
}).catch(console.error);