kaggle.js 3.6 KB
Newer Older
W
init  
wizardforcel 已提交
1 2 3 4
/*
npm install sync-request
npm install cheerio
npm install gen-epub@git+https://github.com/258ch/gen-epub
W
wizardforcel 已提交
5 6
apt install imagemagick
apt install pngquant
W
init  
wizardforcel 已提交
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
*/

var request_ = require('sync-request')
var fs = require('fs')
var {URL} = require('url')
var cheerio = require('cheerio')
var genEpub = require('gen-epub')
var crypto = require('crypto');
var os = require('os')
var path = require('path')
var betterImg = require('./img-better.js')

function requestWithRetry(method, url, kwargs, n=5) {
    
    for(var i = 0; i < n; i++) {
        try {
            return request_(method, url, kwargs)
        } catch(ex) {
            if(i == n - 1) throw ex;
        }
    }
}

function processImg(html, pageUrl, imgs) {
    
    var $ = cheerio.load(html);
    
    var $imgs = $('img');

    for(var i = 0; i < $imgs.length; i++) {
        
        try {
            var $img = $imgs.eq(i);
            var url = $img.attr('src');
            if(!url.startsWith('http'))
                url = new URL(url, pageUrl).toString()
            
            var picname = crypto.createHash('md5').update(url).digest('hex') + ".jpg";
            console.log(`pic: ${url} => ${picname}`)
            
            if(!imgs.has(picname)) {
                var data = request('GET', url).getBody();
W
wizardforcel 已提交
49
                data = betterImg(data, 'tmp')
W
init  
wizardforcel 已提交
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
                imgs.set(picname, data);
            }
            
            $img.attr('src', '../Images/' + picname);
        } catch(ex) {console.log(ex.toString())}
    }
    
    return $.html();

}

var request = requestWithRetry

function getCode(html) {
    var code = /source":(".+?")/.exec(html)[1]
    return '<pre>' + JSON.parse(code) + '</pre>'
}

function getContentUrl(html) {
    return /https?:\/\/www\.kaggleusercontent\.com\/kf\/\d+\/.+?\/__results__\.html/.exec(html)[0]
}

function getBody(html) {
    
    return cheerio.load(html)('body').html()
}

function getToc(id) {
    
    var url = `https://www.kaggle.com/kernels.json?sortBy=hotness&group=everyone&pageSize=10000&competitionId=${id}`
    var j = request('GET', url).body.toString()
    j = JSON.parse(j)
    return j
}

function compToId(name) {
    var url = `https://www.kaggle.com/c/${name}/kernels`
    var html = request('GET', url).body.toString()
    var id = /kaggle\/(\d+)/.exec(html)[1]
    return id
}

W
wizardforcel 已提交
92 93 94 95 96
function safeMkDir(dir) {
    try {fs.mkdirSync(dir)}
    catch(ex) {}
}

W
init  
wizardforcel 已提交
97 98 99 100 101 102 103 104 105
function main() {
    
    var name = process.argv[2]
    console.log(`name: ${name}`)
    var id = compToId(name)
    console.log(`id: ${id}`)
    var toc = getToc(id)
    var articles = []
    var imgs = new Map()
W
wizardforcel 已提交
106
    safeMkDir('tmp')
W
init  
wizardforcel 已提交
107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131
    for(var it of toc) {
        
        var prefix = 'https://www.kaggle.com'
        var url = prefix + it.scriptUrl
        console.log(`url: ${url}`)
        var html = request('GET', url).body.toString()
        if(it.isNotebook){
            var realUrl = getContentUrl(html)
            var co =  request('GET', realUrl).body.toString()
            co = processImg(co, realUrl, imgs)
            co = getBody(co)
        } else {
            var co = getCode(html)
        }
        var from = `<p>From: <a href='${url}'>${url}</a></p>`
        var score = ''
        if(it.bestPublicScore)
            score = `<p>Score: ${it.bestPublicScore}</p>`
        var au = `<p>Author: <a href='${prefix + it.author.profileUrl}'>${it.author.displayName}</a></p>`
        co = `${from}\n${au}\n${score}\n${co}`
        articles.push({title: it.title, content: co})
    }
    
    articles.splice(0, 0, {title: `Kaggle Kernel - ${name}`, content: ''})
    genEpub(articles, imgs)
W
wizardforcel 已提交
132
    
W
init  
wizardforcel 已提交
133 134 135
}

if(module == require.main) main()