-
Notifications
You must be signed in to change notification settings - Fork 56
/
ZemantaService.js
320 lines (281 loc) · 10.3 KB
/
ZemantaService.js
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
// VIE - Vienna IKS Editables
// (c) 2011 Henri Bergius, IKS Consortium
// (c) 2011 Sebastian Germesin, IKS Consortium
// (c) 2011 Szaby Grünwald, IKS Consortium
// VIE may be freely distributed under the MIT license.
// For all details and documentation:
// http://viejs.org/
// ## VIE - ZemantaService service
// The ZemantaService ...
(function(){
// ## VIE.ZemantaService(options)
// This is the constructor to instantiate a new service to collect
// properties of an entity from Zemanta.
// **Parameters**:
// *{object}* **options** Optional set of fields, ```namespaces```, ```rules```, ```url```, or ```name```.
// **Throws**:
// *nothing*
// **Returns**:
// *{VIE.ZemantaService}* : A **new** VIE.ZemantaService instance.
// **Example usage**:
//
// var service = new vie.ZemantaService({<some-configuration>});
VIE.prototype.ZemantaService = function(options) {
var defaults = {
/* the default name of this service */
name : 'zemanta',
/* you can pass an array of URLs which are then tried sequentially */
url: ["http://api.zemanta.com/services/rest/0.0/"],
timeout : 20000, /* 20 seconds timeout */
namespaces : {
zemanta: "http://s.zemanta.com/ns#"
},
/* default rules that are shipped with this service */
rules : [
{
'left' : [
'?subject a zemanta:Recognition',
'?subject zemanta:object ?object',
'?object owl:sameAs ?entity'
],
'right' : [
'?entity zemanta:hasEntityAnnotation ?subject'
]
}
],
"api_key" : undefined
};
/* the options are merged with the default options */
this.options = jQuery.extend(true, defaults, options ? options : {});
this.vie = null; /* will be set via VIE.use(); */
/* overwrite options.name if you want to set another name */
this.name = this.options.name;
/* basic setup for the ajax connection */
jQuery.ajaxSetup({
converters: {"text application/rdf+json": function(s){return JSON.parse(s);}},
timeout: this.options.timeout
});
};
VIE.prototype.ZemantaService.prototype = {
// ### init()
// This method initializes certain properties of the service and is called
// via ```VIE.use()```.
// **Parameters**:
// *nothing*
// **Throws**:
// *nothing*
// **Returns**:
// *{VIE.ZemantaService}* : The VIE.ZemantaService instance itself.
// **Example usage**:
//
// var service = new vie.ZemantaService({<some-configuration>});
// service.init();
init: function(){
for (var key in this.options.namespaces) {
var val = this.options.namespaces[key];
this.vie.namespaces.add(key, val);
}
this.rules = jQuery.extend([], VIE.Util.transformationRules(this));
this.rules = jQuery.merge(this.rules, (this.options.rules) ? this.options.rules : []);
this.connector = new this.vie.ZemantaConnector(this.options);
/* adding these entity types to VIE helps later the querying */
this.vie.types.addOrOverwrite('zemanta:Recognition', [
/*TODO: add attributes */
]).inherit("owl:Thing");
},
// ### analyze(analyzable)
// This method extracts text from the jQuery element and sends it to Zemanta for analysis.
// **Parameters**:
// *{VIE.Analyzable}* **analyzable** The analyzable.
// **Throws**:
// *{Error}* if an invalid VIE.Findable is passed.
// **Returns**:
// *{VIE.StanbolService}* : The VIE.ZemantaService instance itself.
// **Example usage**:
//
// var service = new vie.ZemantaService({<some-configuration>});
// service.analyzable(
// new vie.Analyzable({element : jQuery("#foo")})
// );
analyze: function(analyzable) {
var service = this;
var correct = analyzable instanceof this.vie.Analyzable;
if (!correct) {throw "Invalid Analyzable passed";}
var element = analyzable.options.element ? analyzable.options.element : jQuery('body');
var text = service._extractText(element);
if (text.length > 0) {
var success = function (results) {
_.defer(function(){
var entities = VIE.Util.rdf2Entities(service, results);
analyzable.resolve(entities);
});
};
var error = function (e) {
analyzable.reject(e);
};
var options = {};
this.connector.analyze(text, success, error, options);
} else {
console.warn("No text found in element.");
analyzable.resolve([]);
}
},
/* this private method extracts the outerHTML from a jQuery element */
_extractText: function (element) {
return jQuery(element).wrap("<div>").parent().html();
}
};
// ## VIE.ZemantaConnector(options)
// The ZemantaConnector is the connection between the VIE Zemanta service
// and the actual ajax calls.
// **Parameters**:
// *{object}* **options** The options.
// **Throws**:
// *nothing*
// **Returns**:
// *{VIE.ZemantaConnector}* : The **new** VIE.ZemantaConnector instance.
// **Example usage**:
//
// var conn = new vie.ZemantaConnector({<some-configuration>});
VIE.prototype.ZemantaConnector = function (options) {
var defaults = {
/* you can pass an array of URLs which are then tried sequentially */
url: ["http://api.zemanta.com/services/rest/0.0/"],
timeout : 20000, /* 20 seconds timeout */
"api_key" : undefined
};
/* the options are merged with the default options */
this.options = jQuery.extend(true, defaults, options ? options : {});
this.options.url = (_.isArray(this.options.url))? this.options.url : [ this.options.url ];
this._init();
this.baseUrl = (_.isArray(options.url))? options.url : [ options.url ];
};
VIE.prototype.ZemantaConnector.prototype = {
// ### _init()
// Basic setup of the Zemanta connector. This is called internally by the constructor!
// **Parameters**:
// *nothing*
// **Throws**:
// *nothing*
// **Returns**:
// *{VIE.ZemantaConnector}* : The VIE.ZemantaConnector instance itself.
_init : function () {
var connector = this;
/* basic setup for the ajax connection */
jQuery.ajaxSetup({
converters: {"text application/rdf+json": function(s){return JSON.parse(s);}},
timeout: connector.options.timeout
});
return this;
},
_iterate : function (params) {
if (!params) { return; }
if (params.urlIndex >= this.options.url.length) {
params.error.call(this, "Could not connect to the given Zemanta endpoints! Please check for their setup!");
return;
}
var retryErrorCb = function (c, p) {
/* in case a Zemanta backend is not responding and
* multiple URLs have been registered
*/
return function () {
console.log("Zemanta connection error", arguments);
p.urlIndex = p.urlIndex+1;
c._iterate(p);
};
}(this, params);
if (typeof exports !== "undefined" && typeof process !== "undefined") {
/* We're on Node.js, don't use jQuery.ajax */
return params.methodNode.call(
this,
params.url.call(this, params.urlIndex, params.args.options),
params.args,
params.success,
retryErrorCb);
}
return params.method.call(
this,
params.url.call(this, params.urlIndex, params.args.options),
params.args,
params.success,
retryErrorCb);
},
// ### analyze(text, success, error, options)
// This method sends the given text to Zemanta returns the result by the success callback.
// **Parameters**:
// *{string}* **text** The text to be analyzed.
// *{function}* **success** The success callback.
// *{function}* **error** The error callback.
// *{object}* **options** Options, like the ```format```, or the ```chain``` to be used.
// **Throws**:
// *nothing*
// **Returns**:
// *{VIE.ZemantaConnector}* : The VIE.ZemantaConnector instance itself.
// **Example usage**:
//
// var conn = new vie.ZemantaConnector(opts);
// conn.analyze("<p>This is some HTML text.</p>",
// function (res) { ... },
// function (err) { ... });
analyze: function(text, success, error, options) {
options = (options)? options : {};
var connector = this;
connector._iterate({
method : connector._analyze,
methodNode : connector._analyzeNode,
success : success,
error : error,
url : function (idx, opts) {
var u = this.options.url[idx].replace(/\/$/, '');
return u;
},
args : {
text : text,
format : options.format || "rdfxml",
options : options
},
urlIndex : 0
});
},
_analyze : function (url, args, success, error) {
jQuery.ajax({
success: function(a, b, c){
var responseData = c.responseText.replace(/<z:signature>.*?<\/z:signature>/, '');
success(responseData);
},
error: error,
url: url,
type: "POST",
dataType: "xml",
data: {
method : "zemanta.suggest",
text : args.text,
format : args.format,
api_key : this.options.api_key,
return_rdf_links : args.options.return_rdf_links
},
contentType: "text/plain",
accepts: {"application/rdf+json": "application/rdf+json"}
});
},
_analyzeNode: function(url, args, success, error) {
var request = require('request');
var r = request({
method: "POST",
uri: url,
body: args.text,
headers: {
Accept: args.format,
'Content-Type': 'text/plain'
}
}, function(err, response, body) {
try {
success({results: JSON.parse(body)});
} catch (e) {
error(e);
}
});
r.end();
}
};
})();