Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

144 eliminar spanglish #153

Merged
merged 4 commits into from
Apr 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
File renamed without changes.
17 changes: 9 additions & 8 deletions questionservice/question-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,10 +43,10 @@ app.get("/questions", async (req, res) => {
req.query.locale = "es";
}
try {
var tematica = req.query.tematica ? req.query.tematica : "all";
var topic = req.query.tematica ? req.query.tematica : "all";
var n = req.query.n ? req.query.n : 10;
var locale = req.query.locale;
var data = gen.getQuestions(tematica, n, locale);
var data = gen.getQuestions(topic, n, locale);
res.json(data);
} catch (error) {
res.status(400).json({ error: error.message });
Expand All @@ -65,13 +65,13 @@ app.post("/questions", async (req, res) => {
return;
}
try {
const temas = tematicas ? JSON.parse(tematicas) : [];
const tematicasValidas =
temas.length !== 0
? temas
const topics = tematicas ? JSON.parse(tematicas) : [];
const validTopics =
topics.length !== 0
? topics
: ["paises", "literatura", "cine", "arte", "programacion", "futbolistas", "clubes", "baloncestistas", "politica", "videojuegos"];
const cantidadPreguntas = parseInt(n, 10);
const data = gen.getQuestionsPost(tematicasValidas, cantidadPreguntas, locale);
const questionCount = parseInt(n, 10);
const data = gen.getQuestionsPost(validTopics, questionCount, locale);
res.json(data);
} catch (error) {
res.status(400).json({ error: error.message });
Expand All @@ -91,6 +91,7 @@ const server = app.listen(port, async () => {
});
});

// Schedule to reload generators data every day at 3:00 AM
cron.schedule("0 3 * * *", async () => {
await gen.loadGenerators();
});
Expand Down
48 changes: 24 additions & 24 deletions questionservice/questionGen/GeneratorChooser.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,59 +4,59 @@ const fs = require("fs");
class GeneratorChooser {
constructor() {
this.generators = new Map();
this.tematicas = [];
this.leer_json("./data/tematicas.json");
this.topics = [];
this.read_json("./data/topics.json");
}

leer_json(ruta) {
read_json(ruta) {
const datos = fs.readFileSync(ruta);
var tematicas = JSON.parse(datos);
var topics = JSON.parse(datos);

for (let i in tematicas) {
var tematica = tematicas[i];
this.tematicas.push(i);
for (let i in topics) {
var topic = topics[i];
this.topics.push(i);
this.generators.set(
i,
new GenericGenerator(
tematica.entity,
tematica.props,
tematica.types,
tematica.preguntas
topic.entity,
topic.props,
topic.types,
topic.preguntas
)
);
}
}

getQuestions(tematica, n, locale) {
if (tematica === "all") {
getQuestions(topic, n, locale) {
if (topic === "all") {
var questions = [];
for (let i = 0; i < n; i++) {
let rand = Math.floor(Math.random() * this.tematicas.length);
let randTematica = this.tematicas[rand];
let q = this.generators.get(randTematica).generateRandomQuestions(1, locale);
let rand = Math.floor(Math.random() * this.topics.length);
let randTopic = this.topics[rand];
let q = this.generators.get(randTopic).generateRandomQuestions(1, locale);
questions.push(q);
}
return questions.flat();
} else {
return this.generators.get(tematica).generateRandomQuestions(n, locale);
return this.generators.get(topic).generateRandomQuestions(n, locale);
}
}

getQuestionsPost(tematicas, n, locale) {
getQuestionsPost(topics, n, locale) {
var questions = [];
for (let i = 0; i < n; i++) {
let rand = Math.floor(Math.random() * tematicas.length);
let randTematica = tematicas[rand];
let q = this.generators.get(randTematica).generateRandomQuestions(1, locale);
let rand = Math.floor(Math.random() * topics.length);
let randTopic = topics[rand];
let q = this.generators.get(randTopic).generateRandomQuestions(1, locale);
questions.push(q);
}
return questions.flat();
}

async loadGenerators() {
for (let i = 0; i < this.tematicas.length; i++) {
var gen = this.generators.get(this.tematicas[i]);
console.log("Cargando temática: " + this.tematicas[i]);
for (let i = 0; i < this.topics.length; i++) {
var gen = this.generators.get(this.topics[i]);
console.log("Loading topic: " + this.topics[i]);
await gen.getData();
await this.#sleep(10000);
}
Expand Down
84 changes: 43 additions & 41 deletions questionservice/questionGen/GenericGenerator.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,26 +20,26 @@ class GenericGenerator {
this.preguntasMap = this.#generateQuestionLabels(preguntas);

Array.prototype.groupByEntity = function () {
return this.reduce((acumulador, actual) => {
return this.reduce((acc, actual) => {
const entity = actual.entityLabel.value;
if (!/^Q\d+/.test(entity)) {
if (!acumulador[entity]) {
acumulador[entity] = {};
if (!acc[entity]) {
acc[entity] = {};
}

for (const key in actual) {
if (key !== "entityLabel") {
const valor = actual[key].value;
if (!acumulador[entity][key]) {
acumulador[entity][key] = [valor];
} else if (!acumulador[entity][key].includes(valor)) {
acumulador[entity][key].push(valor);
if (!acc[entity][key]) {
acc[entity][key] = [valor];
} else if (!acc[entity][key].includes(valor)) {
acc[entity][key].push(valor);
}
}
}
}

return acumulador;
return acc;
}, {});
};
}
Expand Down Expand Up @@ -68,7 +68,6 @@ class GenericGenerator {
return map;
}

// Función para realizar la consulta SPARQL y obtener los datos de Wikidata
async getData() {
for (let i = 0; i < LANGUAGES.length; i++) {
const sparqlQuery = `
Expand Down Expand Up @@ -96,60 +95,61 @@ class GenericGenerator {
this.data[LANGUAGES[i]] = data.results.bindings.groupByEntity();
})
.catch((error) => {
console.error("Error fetching data: " + error.message);
console.error("Error fetching data: " + error.monthsage);
});
}
}

generateRandomQuestion(locale) {
// Elegir aleatoriamente una entidad del array
var entidades = Object.keys(this.data[locale]);
const entidadLabel =
entidades[Math.floor(Math.random() * entidades.length)];
// Choose a random entity
var entities = Object.keys(this.data[locale]);
const entityLabel =
entities[Math.floor(Math.random() * entities.length)];

const entidad = this.data[locale][entidadLabel];
const entity = this.data[locale][entityLabel];

// Elegir aleatoriamente una propiedad de la entidad para hacer la pregunta
const propiedades = this.propLabels;
// Choose a random property
const props = this.propLabels;

var respuestaCorrecta = "";
var correctAnswer = "";
var propIndex = 0;
do {
propIndex = Math.floor(Math.random() * propiedades.length);
var propiedadPregunta = propiedades[propIndex];
propIndex = Math.floor(Math.random() * props.length);
var questionProp = props[propIndex];

// Obtener la respuesta correcta
respuestaCorrecta =
entidad[propiedadPregunta][entidad[propiedadPregunta].length - 1];
} while (/^Q\d+/.test(respuestaCorrecta));
// Choose correct answer
correctAnswer =
entity[questionProp][entity[questionProp].length - 1];
} while (/^Q\d+/.test(correctAnswer));

var questionObj = {
pregunta: "",
respuestas: [respuestaCorrecta],
correcta: respuestaCorrecta,
respuestas: [correctAnswer],
correcta: correctAnswer,
};

// Obtener respuestas incorrectas
// Generate incorrect answers
while (questionObj.respuestas.length < 4) {
const otroPaisLabel =
entidades[Math.floor(Math.random() * entidades.length)];
entities[Math.floor(Math.random() * entities.length)];
const otroPais = this.data[locale][otroPaisLabel];
let prop = otroPais[propiedadPregunta][0];
let prop = otroPais[questionProp][0];

// Si no está en las propiedades de la entidad de la pregunta
// If the property is already in the answers array, choose another one
if (
!questionObj.respuestas.includes(prop) &&
!entidad[propiedadPregunta].includes(prop) &&
!entity[questionProp].includes(prop) &&
!/^Q\d+/.test(prop) &&
entidadLabel != prop
entityLabel != prop
) {
questionObj.respuestas.push(prop);
}
}

// Barajar las opciones de respuesta
// Shuffle answers
questionObj.respuestas.sort(() => Math.random() - 0.5);

// Format answers
switch (this.types[propIndex]) {
case "date":
questionObj.respuestas = questionObj.respuestas.map((x) =>
Expand All @@ -166,9 +166,11 @@ class GenericGenerator {
default:
break;
}

// Generate question
questionObj.pregunta = this.preguntasMap
.get(propiedadPregunta)
[locale].replace("%", entidadLabel);
.get(questionProp)
[locale].replace("%", entityLabel);

return questionObj;
}
Expand All @@ -184,21 +186,21 @@ class GenericGenerator {
return questions;
}

#dateFormatter(fecha) {
#dateFormatter(date) {
var isAC = false;
if (fecha.startsWith("-")) {
if (date.startsWith("-")) {
isAC = true;
fecha = fecha.substring(1);
date = date.substring(1);
}

const [año, mes, dia] = fecha
const [year, month, day] = date
.split("T")[0]
.split("-")
.map((n) => Number.parseInt(n).toFixed());

const fechaFormateada = `${dia}/${mes}/${año}${isAC ? " a.C." : ""}`;
const dateFormat = `${day}/${month}/${year}${isAC ? " a.C." : ""}`;

return fechaFormateada;
return dateFormat;
}
}

Expand Down
4 changes: 2 additions & 2 deletions statsservice/stats-service.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ app.post("/saveGame", async (req, res) => {
gamemode == "bateria" ||
gamemode == "calculadora"
) {
// Buscar las estadísticas existentes del usuario y modo de juego
// Search for existing stats
let stats = await Stats.findOne({
username: username,
gamemode: gamemode,
Expand All @@ -56,7 +56,7 @@ app.post("/saveGame", async (req, res) => {
(gameData.incorrectAnswers + gameData.correctAnswers)) *
100;
}
// Si no existen estadísticas, crear un nuevo documento
// If no stats found, create new stats
stats = new Stats({
username: username,
gamemode: gamemode,
Expand Down
Loading
Loading