fix: goodjudgmentopen type

This commit is contained in:
NunoSempere 2022-10-09 12:47:25 +01:00
parent e4a3f38ddf
commit 0cddbf69b0

View File

@ -1,12 +1,13 @@
/* Imports */
import axios from "axios";
import { Tabletojson } from "tabletojson";
import {Tabletojson} from "tabletojson";
import { average } from "../../utils";
import { applyIfSecretExists } from "../utils/getSecrets";
import { sleep } from "../utils/sleep";
import {average} from "../../utils";
import {applyIfSecretExists} from "../utils/getSecrets";
import {sleep} from "../utils/sleep";
import toMarkdown from "../utils/toMarkdown";
import { FetchedQuestion, Platform } from "./";
import {FetchedQuestion, Platform} from "./";
import {FullQuestionOption} from "../../common/types";
/* Definitions */
const platformName = "goodjudgmentopen";
@ -24,33 +25,33 @@ const id = () => 0;
/* Support functions */
function cleanDescription(text: string) {
function cleanDescription(text : string) {
let md = toMarkdown(text);
let result = md.replaceAll("---", "-").replaceAll(" ", " ");
return result;
}
async function fetchPage(page: number, cookie: string) {
async function fetchPage(page : number, cookie : string) {
const response: string = await axios({
url: htmlEndPoint + page,
method: "GET",
headers: {
Cookie: cookie,
},
Cookie: cookie
}
}).then((res) => res.data);
//console.log(response)
// console.log(response)
return response;
}
async function fetchStats(questionUrl: string, cookie: string) {
async function fetchStats(questionUrl : string, cookie : string) {
let response: string = await axios({
url: questionUrl + "/stats",
method: "GET",
headers: {
"Content-Type": "text/html",
Cookie: cookie,
Referer: questionUrl,
},
Referer: questionUrl
}
}).then((res) => res.data);
if (response.includes("Sign up or sign in to forecast")) {
@ -61,9 +62,7 @@ async function fetchStats(questionUrl: string, cookie: string) {
// Parse the embedded json
let htmlElements = response.split("\n");
let jsonLines = htmlElements.filter((element) =>
element.includes("data-react-props")
);
let jsonLines = htmlElements.filter((element) => element.includes("data-react-props"));
let embeddedJsons = jsonLines.map((jsonLine, i) => {
let innerJSONasHTML = jsonLine.split('data-react-props="')[1].split('"')[0];
let json = JSON.parse(innerJSONasHTML.replaceAll(""", '"'));
@ -76,27 +75,11 @@ async function fetchStats(questionUrl: string, cookie: string) {
let numforecasters = firstEmbeddedJson.question.predictors_count;
let numforecasts = firstEmbeddedJson.question.prediction_sets_count;
let questionType = firstEmbeddedJson.question.type;
if (
questionType.includes("Binary") ||
questionType.includes("NonExclusiveOpinionPoolQuestion") ||
questionType.includes("Forecast::Question") ||
!questionType.includes("Forecast::MultiTimePeriodQuestion")
) {
options = firstEmbeddedJson.question.answers.map((answer: any) => ({
name: answer.name,
probability: answer.normalized_probability,
type: "PROBABILITY",
}));
if (questionType.includes("Binary") || questionType.includes("NonExclusiveOpinionPoolQuestion") || questionType.includes("Forecast::Question") || ! questionType.includes("Forecast::MultiTimePeriodQuestion")) {
options = firstEmbeddedJson.question.answers.map((answer : any) => ({name: answer.name, probability: answer.normalized_probability, type: "PROBABILITY"}));
if (options.length == 1 && options[0].name == "Yes") {
let probabilityNo =
options[0].probability > 1
? 1 - options[0].probability / 100
: 1 - options[0].probability;
options.push({
name: "No",
probability: probabilityNo,
type: "PROBABILITY",
});
let probabilityNo = options[0].probability > 1 ? 1 - options[0].probability / 100 : 1 - options[0].probability;
options.push({name: "No", probability: probabilityNo, type: "PROBABILITY"});
}
}
let result = {
@ -105,30 +88,28 @@ async function fetchStats(questionUrl: string, cookie: string) {
qualityindicators: {
numforecasts: Number(numforecasts),
numforecasters: Number(numforecasters),
comments_count: Number(comments_count),
},
comments_count: Number(comments_count)
}
};
// console.log(JSON.stringify(result, null, 4));
return result;
}
function isSignedIn(html: string) {
let isSignedInBool = !(
html.includes("You need to sign in or sign up before continuing") ||
html.includes("Sign up")
);
function isSignedIn(html : string) {
let isSignedInBool = !(html.includes("You need to sign in or sign up before continuing") || html.includes("Sign up"));
// console.log(html)
if (!isSignedInBool) {
if (! isSignedInBool) {
console.log("Error: Not signed in.");
}
console.log(`is signed in? ${isSignedInBool ? "yes" : "no"}`);
console.log(`is signed in? ${
isSignedInBool ? "yes" : "no"
}`);
return isSignedInBool;
}
function reachedEnd(html: string) {
function reachedEnd(html : string) {
let reachedEndBool = html.includes("No questions match your filter");
if (reachedEndBool) {
//console.log(html)
if (reachedEndBool) { // console.log(html)
}
console.log(`Reached end? ${reachedEndBool}`);
return reachedEndBool;
@ -136,7 +117,7 @@ function reachedEnd(html: string) {
/* Body */
async function goodjudgmentopen_inner(cookie: string) {
async function goodjudgmentopen_inner(cookie : string) {
let i = 1;
let response = await fetchPage(i, cookie);
@ -144,7 +125,7 @@ async function goodjudgmentopen_inner(cookie: string) {
let init = Date.now();
// console.log("Downloading... This might take a couple of minutes. Results will be shown.")
console.log("Page #1")
while (!reachedEnd(response) && isSignedIn(response)) {
while (! reachedEnd(response) && isSignedIn(response)) {
let htmlLines = response.split("\n");
DEBUG_MODE == "on" ? htmlLines.forEach((line) => console.log(line)) : id();
let h5elements = htmlLines.filter((str) => str.includes("<h5> <a href="));
@ -153,20 +134,19 @@ async function goodjudgmentopen_inner(cookie: string) {
for (let h5element of h5elements) {
let h5elementSplit = h5element.split('"><span>');
let url = h5elementSplit[0].split('<a href="')[1];
if (!annoyingPromptUrls.includes(url)) {
if (! annoyingPromptUrls.includes(url)) {
let title = h5elementSplit[1].replace("</span></a></h5>", "");
await sleep(1000 + Math.random() * 1000); // don't be as noticeable
try {
let moreinfo = await fetchStats(url, cookie);
if (moreinfo.isbinary) {
if (!moreinfo.crowdpercentage) {
// then request again.
/*if (moreinfo.isbinary) {
if (! moreinfo.crowdpercentage) { // then request again.
moreinfo = await fetchStats(url, cookie);
}
}
}*/
let questionNumRegex = new RegExp("questions/([0-9]+)");
const questionNumMatch = url.match(questionNumRegex);
if (!questionNumMatch) {
if (! questionNumMatch) {
throw new Error(`Couldn't find question num in ${url}`);
}
let questionNum = questionNumMatch[1];
@ -176,21 +156,19 @@ async function goodjudgmentopen_inner(cookie: string) {
title: title,
url: url,
platform: platformName,
...moreinfo,
... moreinfo
};
if (j % 30 == 0 || DEBUG_MODE == "on") {
console.log(`Page #${i}`);
console.log(question);
}else{
} else {
console.log(question.title)
}
// console.log(question)
results.push(question);
} catch (error) {
console.log(error);
console.log(
`We encountered some error when fetching the URL: ${url}, so it won't appear on the final json`
);
console.log(`We encountered some error when fetching the URL: ${url}, so it won't appear on the final json`);
}
}
j = j + 1;
@ -203,9 +181,7 @@ async function goodjudgmentopen_inner(cookie: string) {
response = await fetchPage(i, cookie);
} catch (error) {
console.log(error);
console.log(
`We encountered some error when fetching page #${i}, so it won't appear on the final json`
);
console.log(`We encountered some error when fetching page #${i}, so it won't appear on the final json`);
}
}
@ -216,9 +192,11 @@ async function goodjudgmentopen_inner(cookie: string) {
let end = Date.now();
let difference = end - init;
console.log(
`Took ${difference / 1000} seconds, or ${difference / (1000 * 60)} minutes.`
);
console.log(`Took ${
difference / 1000
} seconds, or ${
difference / (1000 * 60)
} minutes.`);
return results;
}
@ -230,23 +208,18 @@ export const goodjudgmentopen: Platform = {
version: "v1",
async fetcher() {
let cookie = process.env.GOODJUDGMENTOPENCOOKIE;
return (await applyIfSecretExists(cookie, goodjudgmentopen_inner)) || null;
return(await applyIfSecretExists(cookie, goodjudgmentopen_inner)) || null;
},
calculateStars(data) {
let minProbability = Math.min(
...data.options.map((option) => option.probability || 0)
);
let maxProbability = Math.max(
...data.options.map((option) => option.probability || 0)
);
let minProbability = Math.min(...data.options.map((option) => option.probability || 0));
let maxProbability = Math.max(...data.options.map((option) => option.probability || 0));
let nuno = () => ((data.qualityindicators.numforecasts || 0) > 100 ? 3 : 2);
let eli = () => 3;
let misha = () =>
minProbability > 0.1 || maxProbability < 0.9 ? 3.1 : 2.5;
let misha = () => minProbability > 0.1 || maxProbability < 0.9 ? 3.1 : 2.5;
let starsDecimal = average([nuno(), eli(), misha()]);
let starsInteger = Math.round(starsDecimal);
return starsInteger;
},
}
};