-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathtscanclient.py
More file actions
200 lines (163 loc) · 5.96 KB
/
Copy pathtscanclient.py
File metadata and controls
200 lines (163 loc) · 5.96 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
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
#!/usr/bin/env python3
# Simple client example application to talk to the T-scan clamservice
import os
import time
from typing import Iterable, Optional
from dataclasses import dataclass
import requests
from xml.etree import ElementTree
username = input("👤 Username: ")
password = input("🔒 Password: ")
address = "https://tscan.hum.uu.nl/tscan"
@dataclass
class Project:
name: str
status: int # 0 = staging 1 = scanning 2 = done
statusmsg: str
completion: int
time: Optional[str] = None
size: Optional[float] = None
def get_projects() -> Iterable[Project]:
session = requests.Session()
session.auth = (username, password)
response = session.get(address + '/index')
tree = ElementTree.fromstring(response.content)
projects = tree.iterfind('*/project')
for project in projects:
attrib = project.attrib
href = attrib['{http://www.w3.org/1999/xlink}href']
yield Project(
name=href.replace(f'{address}/', ''),
time=attrib['time'],
size=attrib['size'],
status=attrib['status'],
statusmsg='',
completion=0)
def get_project(project: str) -> Project:
session = requests.Session()
session.auth = (username, password)
response = session.get(f'{address}/{project}')
tree = ElementTree.fromstring(response.content)
access_token = tree.attrib['accesstoken']
data = requests.get(f'{address}/{project}/status/?accesstoken={access_token}&user={username}').json()
return Project(
name=project,
status=data['statuscode'],
statusmsg=data['statusmsg'],
completion=data['completion']
)
def create_project(name: str) -> bool:
session = requests.Session()
session.auth = (username, password)
return session.put(address + '/' + name).status_code == 200
def delete_project(name: str) -> bool:
session = requests.Session()
session.auth = (username, password)
return session.delete(address + '/' + name).status_code == 200
def add_input(project: str, name: str, contents: str) -> bool:
session = requests.Session()
session.auth = (username, password)
response = session.post(
f"{address}/{project}/input/{name}.txt",
params={
'inputtemplate': 'textinput',
'contents': contents
})
return response.status_code == 200
def scan(project: str) -> bool:
session = requests.Session()
session.auth = (username, password)
return session.post(
f'{address}/{project}',
params={
'overlapSize': '50',
'frequencyClip': '99.0',
'mtldThreshold': '0.72',
'useAlpino': 'yes',
'useWopr': 'no',
'sentencePerLine': 'no',
'prevalence': 'nl',
'word_freq_lex': 'subtlex_words.freq',
'lemma_freq_lex': 'freqlist_staphorsius_CLIB_lemma.freq',
'top_freq_lex': 'SoNaR500.wordfreqlist20000.freq'
}).ok
def get_project_filenames(project: str) -> Iterable[str]:
session = requests.Session()
session.auth = (username, password)
response = session.get(f'{address}/{project}')
tree = ElementTree.fromstring(response.content)
filenames = tree.iterfind('output/file/name')
for filename in filenames:
yield filename.text
def save_output_file(project: str, filename: str) -> None:
session = requests.Session()
session.auth = (username, password)
response = session.get(f'{address}/{project}/output/{filename}')
os.makedirs(os.path.join('output', project), exist_ok=True)
with open(os.path.join('output', project, filename), 'wb') as target:
target.write(response.content)
def save_output_zip(project: str) -> None:
session = requests.Session()
session.auth = (username, password)
response = session.get(f'{address}/{project}/output/zip')
os.makedirs('output', exist_ok=True)
with open(os.path.join('output', f'{project}.zip'), 'wb') as target:
target.write(response.content)
#
#
# The functions above can now be used to manage T-scan
# Example below:
#
#
print(f"List of {username}'s projects:\n")
for project in get_projects():
print(project.name)
project_name = input("\n\nNew project name? ")
if create_project(project_name):
print("Created project!")
success = add_input(project_name, "example1", """Dit is een test.
En hier is nog een zin.""")
success |= add_input(project_name, "example2", """Hier is wat meer tekst.
En dan nog een zin!""")
if not success:
print('Could not create example files')
exit(1)
scan(project_name)
current_completion = -1
current_statusmsg = ''
current_status = -1
# Wait for the project to be scanned
while True:
project = get_project(project_name)
if project.completion != current_completion or \
project.statusmsg != current_statusmsg or \
project.status != current_status:
current_completion = project.completion
current_statusmsg = project.statusmsg
current_status = project.status
print(f'Scanning {current_completion}% STATUS={current_status} MSG={current_statusmsg}')
if project.status == 2 or project.completion >= 100:
break
time.sleep(10)
# Download the results!
# Maybe this step will fail for very large projects?
# Directly download the files you need below
# You will probably know how they should be called
print("Downloading files...")
filenames = get_project_filenames(project_name)
for file in filenames:
print(file)
save_output_file(project_name, file)
# This should contain the same contents, but conveniently downloaded as a single
# ZIP-file... this will probably work better for projects with
# many small files
print("Downloading zip file")
save_output_zip(project_name)
print("DONE! 🎉")
while True:
should_delete = input("Delete project (y/N)? ")
if not should_delete or should_delete.strip().lower() == "n":
break
elif should_delete.strip().lower() == "y":
delete_project(project_name)
break