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 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290
|
#!/usr/bin/env python
#-*- coding:utf-8 -*-
#Frog Wrapper with XML input and FoLiA output support
from __future__ import print_function, unicode_literals, division, absolute_import
import getopt
import lxml.etree
import sys
import os
import codecs
if __name__ == "__main__":
sys.path.append(sys.path[0] + '/../..')
os.environ['PYTHONPATH'] = sys.path[0] + '/../..'
import pynlpl.formats.folia as folia
from pynlpl.clients.frogclient import FrogClient
def legacyout(i, word,lemma,morph,pos):
if word:
out = str(i + 1) + "\t" + word + "\t" + lemma + "\t" + morph + "\t" + pos
print(out.encode('utf-8'))
else:
print()
def usage():
print >>sys.stderr,"frogwrapper.py [options]"
print >>sys.stderr,"------------------------------------------------------"
print >>sys.stderr,"Input file:"
print >>sys.stderr,"\t--txt=[file] Plaintext input"
print >>sys.stderr,"\t--xml=[file] XML Input"
print >>sys.stderr,"\t--folia=[file] FoLiA XML Input"
print >>sys.stderr,"Frog settings:"
print >>sys.stderr,"\t-p [port] Port the Frog server is running on"
print >>sys.stderr,"Output type:"
print >>sys.stderr,"\t--id=[ID] ID for outputted FoLiA XML Document"
print >>sys.stderr,"\t--legacy Use legacy columned output instead of FoLiA"
print >>sys.stderr,"\t-o Write output to input file (only works for --folia)"
print >>sys.stderr,"XML Input:"
print >>sys.stderr,"\t--selectsen=[expr] Use xpath expression to select sentences"
print >>sys.stderr,"\t--selectpar=[expr] Use xpath expression to select paragraphs"
print >>sys.stderr,"\t--idattrib=[attrb] Copy ID from this attribute"
print >>sys.stderr,"Text Input:"
print >>sys.stderr,"\t-N No structure"
print >>sys.stderr,"\t-S One sentence per line (strict)"
print >>sys.stderr,"\t-P One paragraph per line"
print >>sys.stderr,"\t-I Value in first column (tab seperated) is ID!"
print >>sys.stderr,"\t-E [encoding] Encoding of input file (default: utf-8)"
try:
opts, files = getopt.getopt(sys.argv[1:], "hSPINEp:o", ["txt=","xml=", "folia=","id=",'legacy','tok','selectsen=','selectpar=','idattrib='])
except getopt.GetoptError as err:
# print help information and exit:
print(str(err))
usage()
sys.exit(1)
textfile = xmlfile = foliafile = None
foliaid = 'UNTITLED'
legacy = None
tok = False
idinfirstcolumn = False
encoding = 'utf-8'
mode='s'
xpathselect = ''
idattrib=''
port = None
save = False
for o, a in opts:
if o == "-h":
usage()
sys.exit(0)
elif o == "-I":
idinfirstcolumn = True
elif o == "-S":
mode = 's'
elif o == "-P":
mode = 'p'
elif o == "-p":
port = int(a)
elif o == "-N":
mode = 'n'
elif o == "-E":
encoding = a
elif o == "--selectsen":
mode='s'
xpathselect = a
elif o == "--selectpar":
mode='p'
xpathselect = a
elif o == "--idattrib":
idattrib = a
elif o == "--txt":
textfile = a
elif o == "--xml":
xmlfile = a
elif o == "--folia":
foliafile = a
elif o == "--id":
foliaid = a #ID
elif o == "-o":
save = True
elif o == "--legacy":
legacy = True
elif o == "--tok":
tok = True
else:
print >>sys.stderr, "ERROR: Unknown option:",o
sys.exit(1)
if not port:
print >> sys.stderr,"ERROR: No port specified to connect to Frog server"
sys.exit(2)
elif (not textfile and not xmlfile and not foliafile):
print >> sys.stderr,"ERROR: Specify a file with either --txt, --xml or --folia"
sys.exit(2)
elif xmlfile and not xpathselect:
print >> sys.stderr,"ERROR: You need to specify --selectsen or --selectpar when using --xml"
sys.exit(2)
frogclient = FrogClient('localhost',port)
idmap = []
data = []
if textfile:
f = codecs.open(textfile, 'r', encoding)
for line in f.readlines():
if idinfirstcolumn:
id, line = line.split('\t',1)
idmap.append(id.strip())
else:
idmap.append(None)
data.append(line.strip())
f.close()
if xmlfile:
xmldoc = lxml.etree.parse(xmlfile)
for node in xmldoc.xpath(xpathselect):
if idattrib:
if idattrib in node.attrib:
idmap.append(node.attrib[idattrib])
else:
print >>sys.stderr,"WARNING: Attribute " + idattrib + " not found on node!"
idmap.append(None)
else:
idmap.append(None)
data.append(node.text)
if foliafile:
foliadoc = folia.Document(file=foliafile)
if not foliadoc.declared(folia.AnnotationType.TOKEN):
foliadoc.declare(folia.AnnotationType.TOKEN, set='http://ilk.uvt.nl/folia/sets/ucto-nl.foliaset', annotator='Frog',annotatortype=folia.AnnotatorType.AUTO)
if not foliadoc.declared(folia.AnnotationType.POS):
foliadoc.declare(folia.AnnotationType.POS, set='http://ilk.uvt.nl/folia/sets/cgn-legacy.foliaset', annotator='Frog',annotatortype=folia.AnnotatorType.AUTO)
if not foliadoc.declared(folia.AnnotationType.LEMMA):
foliadoc.declare(folia.AnnotationType.LEMMA, set='http://ilk.uvt.nl/folia/sets/mblem-nl.foliaset', annotator='Frog',annotatortype=folia.AnnotatorType.AUTO)
foliadoc.language('nld')
text = foliadoc.data[-1]
for p in foliadoc.paragraphs():
found_s = False
for s in p.sentences():
found_w = False
for w in s.words():
found_w = True
found_s = True
if found_w:
#pass tokenised sentence
words = s.words()
response = frogclient.process(" ".join([unicode(w) for w in words]))
for i, (word, lemma, morph, pos) in enumerate(response):
if legacy: legacyout(i,word,lemma,morph,pos)
if unicode(words[i]) == word:
if lemma:
words[i].append( folia.LemmaAnnotation(foliadoc, cls=lemma) )
if pos:
words[i].append( folia.PosAnnotation(foliadoc, cls=pos) )
else:
print >>sys.stderr,"WARNING: Out of sync after calling Frog! ", i, word
else:
#pass untokenised sentence
try:
sentext = s.text()
except folia.NoSuchText:
continue
response = frogclient.process(sentext)
for i, (word, lemma, morph, pos) in enumerate(response):
if legacy: legacyout(i,word,lemma,morph,pos)
if word:
w = folia.Word(foliadoc, text=word, generate_id_in=s)
if lemma:
w.append( folia.LemmaAnnotation(foliadoc, cls=lemma) )
if pos:
w.append( folia.PosAnnotation(foliadoc, cls=pos) )
s.append(w)
if not found_s:
#pass paragraph
try:
partext = p.text()
except folia.NoSuchText:
continue
s = folia.Sentence(foliadoc, generate_id_in=p)
response = frogclient.process(partext)
for i, (word, lemma, morph, pos) in enumerate(response):
if (not word or i == len(response) - 1) and len(s) > 0:
#gap or end of response: terminate sentence
p.append(s)
s = folia.Sentence(foliadoc, generate_id_in=p)
elif word:
w = folia.Word(foliadoc, text=word, generate_id_in=s)
if lemma:
w.append( folia.LemmaAnnotation(foliadoc, cls=lemma) )
if pos:
w.append( folia.PosAnnotation(foliadoc, cls=pos) )
s.append(w)
else:
foliadoc = folia.Document(id=foliaid)
foliadoc.declare(folia.AnnotationType.TOKEN, set='http://ilk.uvt.nl/folia/sets/ucto-nl.foliaset', annotator='Frog',annotatortype=folia.AnnotatorType.AUTO)
foliadoc.declare(folia.AnnotationType.POS, set='http://ilk.uvt.nl/folia/sets/cgn-legacy.foliaset', annotator='Frog',annotatortype=folia.AnnotatorType.AUTO)
foliadoc.declare(folia.AnnotationType.LEMMA, set='http://ilk.uvt.nl/folia/sets/mblem-nl.foliaset', annotator='Frog',annotatortype=folia.AnnotatorType.AUTO)
foliadoc.language('nld')
text = folia.Text(foliadoc, id=foliadoc.id + '.text.1')
foliadoc.append(text)
curid = None
for (fragment, id) in zip(data,idmap):
if mode == 's' or mode == 'n':
if id:
s = folia.Sentence(foliadoc, id=id)
else:
s = folia.Sentence(foliadoc, generate_id_in=text)
elif mode == 'p':
if id:
p = folia.Paragraph(foliadoc, id=id)
else:
p = folia.Paragraph(foliadoc, generate_id_in=text)
s = folia.Sentence(foliadoc, generate_id_in=p)
curid = s.id
response = frogclient.process(fragment)
for i, (word, lemma, morph, pos) in enumerate(response):
if legacy:
legacyout(i,word,lemma,morph,pos)
continue
if word:
w = folia.Word(foliadoc, text=word, generate_id_in=s)
if lemma:
w.append( folia.LemmaAnnotation(foliadoc, cls=lemma) )
if pos:
w.append( folia.PosAnnotation(foliadoc, cls=pos) )
s.append(w)
if (not word or i == len(response) - 1) and len(s) > 0:
#gap or end of response: terminate sentence
if mode == 'p':
p.append(s)
if (i == len(response) - 1):
text.append(p)
elif mode == 'n' or (mode == 's' and i == len(response) - 1):
text.append(s)
elif mode == 's':
continue
if i < len(response) - 1: #not done yet?
#create new sentence
if mode == 'p':
s = folia.Sentence(foliadoc, generate_id_in=p)
elif mode == 'n' and id:
#no id for this unforeseen sentence, make something up
s = folia.Sentence(foliadoc, id=curid+'.X')
print("WARNING: Sentence found that was not in original",file=sys.stderr)
if not legacy:
print(foliadoc.xmlstring())
if save and foliafile:
foliadoc.save()
|