-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathWikidataCache.cs
More file actions
90 lines (78 loc) · 2.6 KB
/
WikidataCache.cs
File metadata and controls
90 lines (78 loc) · 2.6 KB
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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace WikiAccess
{
/// <summary>
/// Class to create a cache of property labels, cutting down on Wikidata traffic.
/// </summary>
class WikidataCache
{
Dictionary<int, string> _Cache = new Dictionary<int, string>();
private readonly string LABELCACHE = Path.GetTempPath() + "WikidataLabelCache";
/// <summary>
/// Constructor. Reads in existing cache from LABELCACHE
/// TODO Error trap for dodgy cache.
/// </summary>
public WikidataCache()
{
if (!File.Exists(LABELCACHE))
File.Create(LABELCACHE).Close();
if (_Cache.Count == 0)
{
using (StreamReader Sr = new StreamReader(LABELCACHE))
{
string PropertyAsString;
int Property;
while ((PropertyAsString = Sr.ReadLine()) != null)
{
Property = Convert.ToInt32(PropertyAsString);
string Description = Sr.ReadLine();
_Cache.Add(Property, Description);
}
}
}
}
public string RetrieveLabel(int qcode)
{
string Description = null;
if (_Cache.TryGetValue(qcode, out Description))
{
return Description;
}
else
{
return LookupLabel(qcode);
}
}
/// <summary>
/// If its a new property, look up label on Wikidata and add to cache.
/// </summary>
/// <param name="qcode"></param>
/// <returns></returns>
private string LookupLabel(int qcode)
{
WikidataIO IO = new WikidataIO();
IO.Action = "wbgetentities";
IO.Format = "json";
IO.Ids = qcode;
IO.Props = "labels";
IO.Languages = "en|en-gb|ro";
WikidataFields Fields = new WikidataFields();
Fields = IO.GetData();
string Name = "";
if (!Fields.Labels.TryGetValue("en-gb", out Name))
if (!Fields.Labels.TryGetValue("en", out Name))
Fields.Labels.TryGetValue("en", out Name);
using (StreamWriter Sw = File.AppendText(LABELCACHE))
{
Sw.WriteLine(qcode);
Sw.WriteLine(Name);
}
_Cache.Add(qcode, Name);
return Name;
}
}
}