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

Wikidata api #81

Merged
merged 4 commits into from
Mar 6, 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
30 changes: 30 additions & 0 deletions wikidata_service/.dockerignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
**/.classpath
**/.dockerignore
**/.env
**/.git
**/.gitignore
**/.project
**/.settings
**/.toolstarget
**/.vs
**/.vscode
**/*.*proj.user
**/*.dbmdl
**/*.jfm
**/azds.yaml
**/bin
**/charts
**/docker-compose*
**/Dockerfile*
**/node_modules
**/npm-debug.log
**/obj
**/secrets.dev.yaml
**/values.dev.yaml
LICENSE
README.md
!**/.gitignore
!.git/HEAD
!.git/config
!.git/packed-refs
!.git/refs/heads/**
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
972 changes: 972 additions & 0 deletions wikidata_service/.vs/WikiDataTest/config/applicationhost.config

Large diffs are not rendered by default.

Binary file added wikidata_service/.vs/WikiDataTest/v17/.futdcache.v2
Binary file not shown.
Binary file added wikidata_service/.vs/WikiDataTest/v17/.suo
Binary file not shown.
25 changes: 25 additions & 0 deletions wikidata_service/WikiDataTest.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.8.34316.72
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WikiDataTest", "WikiDataTest\WikiDataTest.csproj", "{C8146490-E482-406D-852F-5936D5B5BFB9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{C8146490-E482-406D-852F-5936D5B5BFB9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{C8146490-E482-406D-852F-5936D5B5BFB9}.Debug|Any CPU.Build.0 = Debug|Any CPU
{C8146490-E482-406D-852F-5936D5B5BFB9}.Release|Any CPU.ActiveCfg = Release|Any CPU
{C8146490-E482-406D-852F-5936D5B5BFB9}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {E295DB00-B5E6-4400-9C95-B9FB22AAE4AD}
EndGlobalSection
EndGlobal
145 changes: 145 additions & 0 deletions wikidata_service/WikiDataTest/Controllers/WikiDataController.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;

namespace WikiDataTest.Controllers
{
[ApiController]
[Route("[controller]")]
public class WikiDataController : ControllerBase
{
private readonly ILogger<WikiDataController> _logger;

public WikiDataController(ILogger<WikiDataController> logger)
{
_logger = logger;
}

[HttpGet("GetQuestions")]
public async Task<IActionResult> GetQuestions()
{
string endpointUrl = "https://query.wikidata.org/sparql?query=";
string sparqlQuery = "SELECT ?capitalLabel ?countryLabel WHERE { ?capital wdt:P1376 ?country. ?capital wdt:P31 wd:Q5119. ?country wdt:P31 wd:Q3624078. SERVICE wikibase:label { bd:serviceParam wikibase:language \"[AUTO_LANGUAGE],en\". }} LIMIT 400";

var fullUrl = endpointUrl + sparqlQuery;

using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("User-Agent", "Sergiollende/1.0");
client.DefaultRequestHeaders.Add("Accept", "application/sparql-results+json");

HttpResponseMessage response = await client.GetAsync(fullUrl);

string responseBody = await response.Content.ReadAsStringAsync();

RootObject jsonResult = JsonConvert.DeserializeObject<RootObject>(responseBody);
foreach(CapitalCountry c in jsonResult.results.bindings)
{
Console.WriteLine(c.ToString());
}

Question[] questions = GenerateQuestionsCapitalsOf(jsonResult.results.bindings.ToArray<CapitalCountry>());

foreach (var item in questions)
{
Console.WriteLine(item.ToString());
}

return Ok(jsonResult);
}

}

private Question[] GenerateQuestionsCapitalsOf(CapitalCountry[] capitalCountries)
{
Question[] questions = new Question[10];

ISet<int> ids = new HashSet<int>();
Random r = new Random();

while (ids.Count < 10) {
ids.Add(r.Next(capitalCountries.Length));
}

int[] idsList = new int[10];
int i = 0;
foreach (int id in ids)
{
idsList[i++] = id;
}

for (int j = 0; j < idsList.Length; j++)
{
string text = "What is the capital of " + capitalCountries[idsList[j]].countryLabel.value;
string[] answers = new string[4];
answers[0] = capitalCountries[idsList[j]].capitalLabel.value;
int[] wrongIds = new int[3];
for (int w = 1; w < 4; w++)
{
int wrongId = r.Next(capitalCountries.Length);
while (idsList.Contains(wrongId) || wrongIds.Contains(wrongId) )
{
wrongId = r.Next(capitalCountries.Length);
}
answers[w] = capitalCountries[wrongId].capitalLabel.value;
}
int correctAnswer = 0;

questions[j] = new Question(text, answers, correctAnswer);
}

return questions;
}

}

public class CapitalCountry
{
public Label capitalLabel { get; set; }
public Label countryLabel { get; set; }

public string ToString()
{
return countryLabel.value + ": " + capitalLabel.value;
}
}

public class Label
{
public string value { get; set; }
}


public class Results
{
public List<CapitalCountry> bindings { get; set; }
}

public class RootObject
{
public Results results { get; set; }
}

public class Question
{
public string text { get; set; }
public string[] answers;
public int correctAnswer;

public Question(string text, string[] answers, int correctAnswer)
{
this.text = text;
this.answers = answers;
this.correctAnswer = correctAnswer;
}

public string ToString()
{
string aux = "text: " + text;
aux += "\ncorrectAnswer: " + answers[0];
aux += "\nAnswer: " + answers[1];
aux += "\nAnswer: " + answers[2];
aux += "\nAnswer: " + answers[3];
return aux ;
}
}
}
27 changes: 27 additions & 0 deletions wikidata_service/WikiDataTest/Dockerfile
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#See https://aka.ms/customizecontainer to learn how to customize your debug container and how Visual Studio uses this Dockerfile to build your images for faster debugging.

#Depending on the operating system of the host machines(s) that will build or run the containers, the image specified in the FROM statement may need to be changed.
#For more information, please see https://aka.ms/containercompat

FROM mcr.microsoft.com/dotnet/aspnet:6.0 AS base
WORKDIR /app
EXPOSE 80
EXPOSE 443

FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build
ARG BUILD_CONFIGURATION=Release
WORKDIR /src
COPY ["WikiDataTest/WikiDataTest.csproj", "WikiDataTest/"]
RUN dotnet restore "./WikiDataTest/./WikiDataTest.csproj"
COPY . .
WORKDIR "/src/WikiDataTest"
RUN dotnet build "./WikiDataTest.csproj" -c %BUILD_CONFIGURATION% -o /app/build

FROM build AS publish
ARG BUILD_CONFIGURATION=Release
RUN dotnet publish "./WikiDataTest.csproj" -c %BUILD_CONFIGURATION% -o /app/publish /p:UseAppHost=false

FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WikiDataTest.dll"]
25 changes: 25 additions & 0 deletions wikidata_service/WikiDataTest/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();
41 changes: 41 additions & 0 deletions wikidata_service/WikiDataTest/Properties/launchSettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
{
"profiles": {
"WikiDataTest": {
"commandName": "Project",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"dotnetRunMessages": true,
"applicationUrl": "https://localhost:7259;http://localhost:5276"
},
"IIS Express": {
"commandName": "IISExpress",
"launchBrowser": true,
"launchUrl": "swagger",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}
},
"Docker": {
"commandName": "Docker",
"launchBrowser": true,
"launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}/swagger",
"environmentVariables": {
"ASPNETCORE_URLS": "https://+:443;http://+:80"
},
"publishAllPorts": true,
"useSSL": true
}
},
"$schema": "https://json.schemastore.org/launchsettings.json",
"iisSettings": {
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:48168",
"sslPort": 44321
}
}
}
17 changes: 17 additions & 0 deletions wikidata_service/WikiDataTest/WikiDataTest.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
<Project Sdk="Microsoft.NET.Sdk.Web">

<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<UserSecretsId>dc965c48-6b02-4193-ad00-5a708ae03c89</UserSecretsId>
<DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.5" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.5.0" />
</ItemGroup>

</Project>
9 changes: 9 additions & 0 deletions wikidata_service/WikiDataTest/WikiDataTest.csproj.user
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="Current" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<ActiveDebugProfile>WikiDataTest</ActiveDebugProfile>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
<DebuggerFlavor>ProjectDebugger</DebuggerFlavor>
</PropertyGroup>
</Project>
8 changes: 8 additions & 0 deletions wikidata_service/WikiDataTest/appsettings.Development.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
}
}
9 changes: 9 additions & 0 deletions wikidata_service/WikiDataTest/appsettings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Loading