summaryrefslogtreecommitdiff
path: root/conlex.lua
blob: afee98049baa3f6ba1db08ace3658fc2e5452f8a (plain)
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
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#!/usr/bin/env lua5.3
local function template(str, args)
	return (str:gsub("%%(%w+)%%", args))
end

local function urldecode(s)
	return s:gsub('+',' ')
		:gsub('%%(%x%x)',function(x)
			return string.char(tonumber(x,16))
		end)
end
local function parse_qs(s)
	local ix = 1
	local res = {}
	while true do
		local _,next_ix,ek,ev = s:find("([^=]+)=([^&]*)&?",ix)
		if not ek then break end
		local k,v = urldecode(ek), urldecode(ev)
		res[k] = v
		ix = next_ix + 1
	end
	return res
end

local function eprint(...)
	local s = {}
	for i = 1, select('#',...) do
		s[i] = tostring(select(i, ...))
	end
	io.stderr:write(table.concat(s, "\t"), "\n")
end

local document_template
do
	local template_file = assert(io.open"template.html")
	document_template = template_file:read"a"
	template_file:close()
end

local function load_dict(filename)
	local res = {}
	for line in io.lines(filename) do
		local word, pos, def = line:match "^(.-)\t(.-)\t(.-)$"
		if word then
			res[word] = {pos=pos, def=def, word=word}
		end
	end
	return res
end

local function format_def(found_word, entry)
	local defc
	if entry then
		defc = template("<b>%word%</b> <i>%pos%</i>. %def%", entry)
	else
		defc = "????"
	end
	return template(
		"<word><def>%defc%</def><wi>%wi%</wi></word>",
		{defc=defc, wi=found_word}
	)
end

local glossors = {}

function glossors.sanila(text)
	local words = load_dict "sanila.tsv"

	local items = {}
	-- sanila morphology is easy enough
	for word in text:gmatch("%S+") do
		local stripped = word:match("^(.-)[.,]*$")
		local entry = words[stripped]
		table.insert(items, format_def(word, entry))
	end

	return items
end

local function engloss(langue, text)
	local items = glossors[langue](text)
	return template([[
	<section>%text%</section>
	<section id=place></section>]], {text=table.concat(items, "\n")})
end

local function enform()
	return [[
<section>
<form>
	<textarea name=q></textarea>
	<button>perform <i>conlation</i></button>
</form>
</section>]]
end

local function response(content)
	print("Content-Type: text/html")
	print()
	print(template(document_template, {content=content}))
end

local function main()
	local text = nil
	local qs = os.getenv"QUERY_STRING"
	if qs then text = parse_qs(qs).q end

	if not text then
		response(enform())
	else
		response(engloss('sanila', text))
	end
end

main()