-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathTurKit.cs
executable file
·445 lines (386 loc) · 18.7 KB
/
TurKit.cs
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
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Xml.Linq;
using System.Threading;
using Word = Microsoft.Office.Interop.Word;
using Office = Microsoft.Office.Core;
using Microsoft.Office.Tools.Word;
using Microsoft.Office.Tools.Word.Extensions;
using System.Web.Script.Serialization;
using System.Text.RegularExpressions;
using Soylent.Model;
using Soylent.Model.Shortn;
using Soylent.Model.Crowdproof;
using Soylent.Model.HumanMacro;
namespace Soylent
{
public class TurKit
{
private HITData hdata;
public Timer turkitLoopTimer;
private ProcessInformation info;
public static string TURKIT_VERSION = "TurKit-0.2.8.jar";
public static int TIMER_LOOP_SECONDS = 60;
public static int TIMER_LOOP_SECONDS_DEBUG = 30;
public static bool SHOW_WINDOW = false;
/// <summary>
/// Creates a TurKit job for the selected task.
/// </summary>
/// <param name="hdata">The HITData representing the desired job</param>
public TurKit(HITData hdata)
{
this.hdata = hdata;
}
public delegate void startTaskDelegate(AmazonKeys keys);
public delegate void noKeysDelegate(); // called if we couldn't get keys
public void startShortnTask(AmazonKeys keys)
{
startFindFixVerifyTask("shortn", keys);
}
public void startCrowdproofTask(AmazonKeys keys)
{
startFindFixVerifyTask("crowdproof", keys);
}
public void startFindFixVerifyTask(string tasktype, AmazonKeys keys) {
string[][] pgraphs = new string[hdata.range.Paragraphs.Count][];
// Range.Paragraphs and Range.Sentences are 1 INDEXED
for (int i = 0; i < hdata.range.Paragraphs.Count; i++)
{
Word.Paragraph paragraph = hdata.range.Paragraphs[i + 1];
pgraphs[i] = new string[paragraph.Range.Sentences.Count];
for (int j = 0; j < paragraph.Range.Sentences.Count; j++)
{
Word.Range sentence = paragraph.Range.Sentences[j + 1];
string temp = sentence.Text;
// Whitespace characters in the middle of sentences will not be removed
temp = temp.Trim();
pgraphs[i][j] = temp;
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
string paragraphs = js.Serialize(pgraphs);
//string paragraphs = JsonConvert.SerializeObject(pgraphs);
paragraphs = "var paragraphs = " + paragraphs + ";";
// figure out whether there are one or two spaces between sentences
string firstSentence = hdata.range.Paragraphs[1].Range.Sentences[1].Text;
string spacesBetweenSentences = " ";
if (firstSentence.EndsWith(" "))
{
spacesBetweenSentences = " ";
}
string numSpaces = "var sentence_separator = '" + spacesBetweenSentences + "';";
int request = hdata.job;
string requestLine = "var soylentJob = " + request + ";";
string debug = "var debug = " + (Soylent.DEBUG ? "true" : "false") + ";";
string fileDirectory = "var fileDirectory = " + js.Serialize(Soylent.GetAppDirectory() + @"turkit");
string[] script = File.ReadAllLines(Soylent.GetAppDirectory() + @"turkit\templates\"
+ tasktype + @"\" + tasktype + @".data.js");
int new_lines = 5;
string[] newScript = new string[new_lines + script.Length];
newScript[0] = requestLine;
newScript[1] = paragraphs;
newScript[2] = debug;
newScript[3] = numSpaces;
newScript[4] = fileDirectory;
Array.Copy(script, 0, newScript, new_lines, script.Length);
string requestFile = Soylent.GetDataDirectory() + @"active-hits\" + tasktype + @"." + request + ".data.js";
File.WriteAllLines(requestFile, newScript, Encoding.UTF8);
string arguments = " -jar " + TURKIT_VERSION + " -f \"" + requestFile + "\" -a " + keys.amazonID + " -s " + keys.secretKey + " -o 100 -h 1000";
if (Soylent.DEBUG)
{
arguments += " -m sandbox";
}
else
{
arguments += " -m real";
}
info = new ProcessInformation("java", arguments, Soylent.GetAppDirectory() + @"\turkit", SHOW_WINDOW);
TimerCallback callback = ExecuteProcess;
int timer = 60 * 1000;
if (Soylent.DEBUG)
{
timer = 30 * 1000;
}
turkitLoopTimer = new Timer(callback, info, 0, timer); // starts the timer every 60 seconds
}
public void startHumanMacroTask(AmazonKeys keys)
{
HumanMacroData data = hdata as HumanMacroData;
JavaScriptSerializer js = new JavaScriptSerializer();
string inputs;
if (data.separator == HumanMacroData.Separator.Paragraph)
{
string[] pgraphs;
if (data.test == HumanMacroData.TestOrReal.Test)
{
pgraphs = new string[1];
}
else
{
pgraphs = new string[data.range.Paragraphs.Count];
}
for (int i = 0; i < data.range.Paragraphs.Count; i++)
{
Word.Paragraph paragraph = data.range.Paragraphs[i + 1];
string temp = paragraph.Range.Text;
temp = temp.Trim();
pgraphs[i] = temp;
/*
Patch patch = new Patch(paragraph.Range, new List<string>());
patch.original = paragraph.Range.Text;
*/
HumanMacroPatch patch = new HumanMacroPatch(paragraph.Range, paragraph.Range.Start - data.range.Start, paragraph.Range.End - data.range.Start);
patch.original = paragraph.Range.Text;
data.patches.Add(patch);
if (data.test == HumanMacroData.TestOrReal.Test)
{
break;
}
}
inputs = js.Serialize(pgraphs);
}
else
{
string[] pgraphs;
if (data.test == HumanMacroData.TestOrReal.Test)
{
pgraphs = new string[1];
}
else
{
pgraphs = new string[data.range.Sentences.Count];
}
for (int i = 0; i < data.range.Sentences.Count; i++)
{
Word.Range range = data.range.Sentences[i + 1];
string temp = range.Text;
// Whitespace characters in the middle of sentences will not be removed
temp = temp.Trim();
pgraphs[i] = temp;
//Patch patch = new Patch(range, new List<string>());
HumanMacroPatch patch = new HumanMacroPatch(range, range.Start - data.range.Start, range.End - data.range.Start);
patch.original = range.Text;
data.patches.Add(patch);
if (data.test == HumanMacroData.TestOrReal.Test)
{
break;
}
}
inputs = js.Serialize(pgraphs);
}
inputs = "var inputs = " + inputs + ";";
// figure out whether there are one or two spaces between sentences
string firstSentence = data.range.Paragraphs[1].Range.Sentences[1].Text;
string spacesBetweenSentences = " ";
if (firstSentence.EndsWith(" "))
{
spacesBetweenSentences = " ";
}
data.patchesFound(spacesBetweenSentences);
string numSpaces = "var sentence_separator = '" + spacesBetweenSentences + "';";
int request = hdata.job;
string requestLine = "var soylentJob = " + request + ";";
string debug = "var debug = " + (Soylent.DEBUG ? "true" : "false") + ";";
string reward = "var reward = " + data.reward + ";";
string redundancy = "var redundancy = " + data.redundancy + ";";
string title = "var title = '" + data.title + "';";
string subtitle = "var subtitle = '" + data.subtitle + "';";
string instructions = "var instructions = '" + data.instructions + "';";
string[] script = File.ReadAllLines(Soylent.GetAppDirectory() + @"\turkit\templates\human-macro\macro.data.js");
int new_lines = 9;
string[] newScript = new string[new_lines + script.Length];
newScript[0] = requestLine;
newScript[1] = inputs;
newScript[2] = debug;
newScript[3] = numSpaces;
newScript[4] = reward;
newScript[5] = redundancy;
newScript[6] = title;
newScript[7] = subtitle;
newScript[8] = instructions;
Array.Copy(script, 0, newScript, new_lines, script.Length);
string requestFile = Soylent.GetDataDirectory() + @"\active-hits\macro." + request + ".data.js";
File.WriteAllLines(requestFile, newScript, Encoding.UTF8);
string arguments = " -jar " + TURKIT_VERSION + " -f \"" + requestFile + "\" -a " + keys.amazonID + " -s " + keys.secretKey + " -o 100 -h 1000";
if (Soylent.DEBUG)
{
arguments += " -m sandbox";
}
else
{
arguments += " -m real";
}
//ProcessInformation info = new ProcessInformation("java", arguments, rootDirectory + @"\turkit", Soylent.DEBUG);
info = new ProcessInformation("java", arguments, Soylent.GetAppDirectory() + @"\turkit", SHOW_WINDOW);
TimerCallback callback = ExecuteProcess;
int timer = 60 * 1000;
if (Soylent.DEBUG)
{
timer = 30 * 1000;
}
turkitLoopTimer = new Timer(callback, info, 0, timer); // starts the timer every 60 seconds
}
/// <summary>
/// Starts a task. For a Shortn task, this breaks the selected range into appropriate groupings, overwrites the template file, and runs TurKit on a Timer.
/// </summary>
public void startTask(noKeysDelegate cancelDelegate)
{
startTaskDelegate taskDelegate = null;
if (hdata is ShortnData)
{
taskDelegate = startShortnTask;
}
else if (hdata is CrowdproofData)
{
taskDelegate = startCrowdproofTask;
}
else if (hdata is HumanMacroData)
{
taskDelegate = startHumanMacroTask;
}
// Get the Amazon Keys. This might need to pop up a window asking for them. Run the task as a callback when it's complete.
GetKeysAndExecute(taskDelegate, cancelDelegate);
}
public void stopTurKitTimer()
{
if (turkitLoopTimer == null)
{
turkitLoopTimer.Change(Timeout.Infinite, Timeout.Infinite);
}
if (info.process != null && !info.process.HasExited)
{
info.process.Kill(); // release the lock on the file; we don't need TurKit to run any more
}
}
public void cancelTask(AmazonKeys keys)
{
// Stop TurKit timer
stopTurKitTimer();
// Call the cancelTask() method
int request = hdata.job;
string cancelLine = "\n" + "cancelTask();";
if (hdata is ShortnData)
{
string requestFile = Soylent.GetAppDirectory() + @"\turkit\active-hits\shortn." + request + ".data.js";
File.AppendAllText(requestFile, cancelLine);
string arguments = " -jar " + TURKIT_VERSION + " -f \"" + requestFile + "\" -a " + keys.amazonID + " -s " + keys.secretKey + " -o 100 -h 1000";
if (Soylent.DEBUG)
{
arguments += " -m sandbox";
}
else
{
arguments += " -m real";
}
ProcessInformation cancel_info = new ProcessInformation("java", arguments, Soylent.GetAppDirectory() + @"\turkit", SHOW_WINDOW);
ExecuteProcess(cancel_info);
}
else if (hdata is CrowdproofData)
{
string requestFile = Soylent.GetDataDirectory() + @"\active-hits\crowdproof." + request + ".data.js";
File.AppendAllText(requestFile, cancelLine);
string arguments = " -jar " + TURKIT_VERSION + " -f \"" + requestFile + "\" -a " + keys.amazonID + " -s " + keys.secretKey + " -o 100 -h 1000";
if (Soylent.DEBUG)
{
arguments += " -m sandbox";
}
else
{
arguments += " -m real";
}
ProcessInformation cancel_info = new ProcessInformation("java", arguments, Soylent.GetAppDirectory() + @"\turkit", SHOW_WINDOW);
ExecuteProcess(cancel_info);
}
else if (hdata is HumanMacroData)
{
string requestFile = Soylent.GetDataDirectory() + @"\active-hits\macro." + request + ".data.js";
File.AppendAllText(requestFile, cancelLine);
string arguments = " -jar " + TURKIT_VERSION + " -f \"" + requestFile + "\" -a " + keys.amazonID + " -s " + keys.secretKey + " -o 100 -h 1000";
if (Soylent.DEBUG)
{
arguments += " -m sandbox";
}
else
{
arguments += " -m real";
}
ProcessInformation cancel_info = new ProcessInformation("java", arguments, Soylent.GetAppDirectory() + @"\turkit", SHOW_WINDOW);
ExecuteProcess(cancel_info);
}
}
/// <summary>
/// Asks for Amazon Keys if necessary and then executes the task
/// </summary>
/// <param name="taskDelegate"></param>
public void GetKeysAndExecute(startTaskDelegate taskDelegate, noKeysDelegate cancelDelegate)
{
AmazonKeys.AskForAmazonKeys(taskDelegate, cancelDelegate);
}
///<summary>
/// Executes a process and waits for it to end.
///</summary>
///<param name="cmd">Full Path of process to execute.</param>
///<param name="cmdParams">Command Line params of process</param>
///<param name="workingDirectory">Process' working directory</param>
///<param name="timeout">Time to wait for process to end</param>
///<param name="stdOutput">Redirected standard output of process</param>
///<returns>Process exit code</returns>
private void ExecuteProcess(object infoObject)
{
if (info.process != null && !info.process.HasExited)
{
Debug.WriteLine("ExecuteProcess exiting; previous process " + info.process.Id + " for job " + hdata.job + " still running.");
return; // there's another TurKit already running; exit and wait for it to finish
}
Debug.WriteLine("Running process for job " + this.hdata.job);
// TODO: Clearing the error console each time the program runs is a bit of a hack,
// but it's the best time/benefit tradeoff to avoid having error messages
// stick around forever
Microsoft.Office.Interop.Word.Document doc = Globals.Soylent.jobToDoc[hdata.job];
Globals.Soylent.soylentMap[doc].Invoke(new HITData.clearErrorDelegate(hdata.clearErrors), new object[] { });
ProcessInformation execute_info = (ProcessInformation) infoObject;
if (execute_info.showWindow)
{
execute_info.cmdParams = " /k " + execute_info.cmd + execute_info.cmdParams;
execute_info.cmd = "cmd";
}
execute_info.process = new Process();
execute_info.process.StartInfo = new ProcessStartInfo(execute_info.cmd, execute_info.cmdParams);
execute_info.process.StartInfo.WorkingDirectory = execute_info.workingDirectory;
execute_info.process.StartInfo.UseShellExecute = false;
if (!execute_info.showWindow)
{
execute_info.process.StartInfo.CreateNoWindow = true;
execute_info.process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
// NOTICE: if you redirect stdout or stderr, you will need to consume it
// using StandardOutput.ReadToEnd() each time you wake up or the process will never exit.
// E.g., ExecuteProcess reads, then sleeps for 2 seconds so the processes die, then it can move on.
// Recommendation: If you need the output, show the window instead.
execute_info.process.StartInfo.RedirectStandardOutput = false;
execute_info.process.StartInfo.RedirectStandardError = false;
}
execute_info.process.Start();
info.process = execute_info.process;
execute_info.process.WaitForExit();
}
private class ProcessInformation
{
public string cmd { get; set; }
public string cmdParams { get; set; }
public string workingDirectory { get ; set; }
public bool showWindow { get; set; }
public Process process { get; set; }
public ProcessInformation(string cmd, string cmdParams, string workingDirectory, bool showWindow) {
this.cmd = cmd;
this.cmdParams = cmdParams;
this.workingDirectory = workingDirectory;
this.showWindow = showWindow;
this.process = null;
}
}
}
}