-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathgo-wolfram.go
411 lines (334 loc) · 10.9 KB
/
go-wolfram.go
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
package wolfram
import (
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
)
// The client, requires an App ID, which you can sign up for at https://developer.wolframalpha.com/
type Client struct {
AppID string
}
type Json struct {
QueryResult QueryResult `json:"queryresult"`
}
// The QueryResult is what you get back after a request
type QueryResult struct {
//true or false depending on whether the input could be successfully
//understood. If false there will be no <pod> subelements
Success bool `json:"success"`
//true or false depending on whether a serious processing error occurred,
//such as a missing required parameter. If true there will be no pod
//content, just an <error> sub-element.
Error bool `json:"error"`
//The number of pod elements
NumPods int `json:"numpods"`
//Categories and types of data represented in the results
DataTypes string `json:"datatypes"`
//The number of pods that are missing because they timed out (see the
//scantimeout query parameter).
TimedOut string `json:"timedout"`
TimedOutPods string `json:"timedoutpods"`
//The wall-clock time in seconds required to generate the output.
Timing float64 `json:"timing"`
//The time in seconds required by the parsing phase.
ParseTiming float64 `json:"parsetiming"`
//Whether the parsing stage timed out (try a longer parsetimeout parameter
//if true)
ParseTimedOut bool `json:"parsetimedout"`
//A URL to use to recalculate the query and get more pods.
ReCalculate string `json:"recalculate"`
//These elements are not documented currently
ID string `json:"id"`
Host string `json:"host"`
Server string `json:"server"`
Related string `json:"related"`
//The version specification of the API on the server that produced this result.
Version string `json:"version"`
InputString string `json:"inputstring"`
//The pods are what hold the majority of the information
Pods []Pod `json:"pods"`
//Each Source contains a link to a web page with the source information
// EDIT: it's variable. Can be an array or an object alone. Then this fails sometimes and sometimes not. So I
// disabled it.
//Sources []Source `json:"sources"`
}
type Generalization struct {
Topic string `json:"topic"`
Description string `json:"desc"`
URL string `json:"url"`
}
type Warnings struct {
//How many warnings were issued
Count int `json:"count"`
//Suggestions for spelling corrections
Spellchecks []Spellcheck `json:"spellcheck"`
//"If you enter a query with mismatched delimiters like "sin(x", Wolfram|Alpha attempts to fix the problem and reports
//this as a warning."
Delimiters []Delimiters `json:"delimiters"`
//"[The API] will translate some queries from non-English languages into English. In some cases when it does
//this, you will get a <translation> element in the API result."
Translations []Translation `json:"translation"`
//"[The API] can automatically try to reinterpret a query that it does not understand but that seems close to one
//that it can."
ReInterpretations []ReInterpretation `json:"reinterpret"`
}
type Spellcheck struct {
Word string `json:"word"`
Suggestion string `json:"suggestion"`
Text string `json:"text"`
}
type Delimiters struct {
Text string `json:"text"`
}
type Translation struct {
Phrase string `json:"phrase"`
Translation string `json:"trans"`
Language string `json:"lang"`
Text string `json:"text"`
}
type ReInterpretation struct {
Alternatives []Alternative `json:"alternative"`
Text string `json:"text"`
New string `json:"new"`
}
type Alternative struct {
InnerText string `json:",innerxml"`
}
type Assumptions struct {
Assumption []Assumption `json:"assumption"`
Count int `json:"count"`
}
type Assumption struct {
Values []Value `json:"value"`
Type string `json:"type"`
Word string `json:"word"`
Template string `json:"template"`
Count int `json:"count"`
}
// Usually contains info about an assumption
type Value struct {
Name string `json:"name"`
Word string `json:"word"`
Description string `json:"desc"`
Input string `json:"input"`
}
// <pod> elements are subelements of <queryresult>. Each contains the results for a single pod
type Pod struct {
//The pod title, used to identify the pod.
Title string `json:"title"`
//The name of the scanner that produced this pod. A guide to the type of
//data it holds.
Scanner string `json:"scanner"`
//Not documented currently
ID string `json:"id"`
Position int `json:"position"`
Error bool `json:"error"`
NumSubPods int `json:"numsubpods"`
//Marks the pod that displays the closest thing to a simple "answer" that Wolfram|Alpha can provide
Primary bool `json:"primary,omitempty"`
//The subpod elements of the pod
SubPods []SubPod `json:"subpods"`
//sub elements of the pod
States []State `json:"states"`
}
// If there was a sound related to the query, if you for example query a musical note
// You will get a <sound> element which contains a link to the sound
type Sounds struct {
Count int `json:"count"`
Sound []Sound `json:"sound"`
}
type Sound struct {
URL string `json:"url"`
Type string `json:"type"`
}
// If there's extra information for the pod, the pod will have a <infos> element
// which contains <info> elements with text, and/or images/links to that information
type Infos struct {
Count int `json:"count"`
Info []Info `json:"info"`
}
type Info struct {
Text string `json:"text"`
Img []Img `json:"img"`
Link []Link `json:"link"`
}
type Link struct {
URL string `json:"url"`
Text string `json:"text"`
Title string `json:"title"`
}
// Source contains a link to a web page with the source information
type Source struct {
URL string `json:"url"`
Text string `json:"text"`
}
// "Many pods on the Wolfram|Alpha website have text buttons in their upper-right corners that substitute the
// contents of that pod with a modified version. In Figure 1, the Result pod has buttons titled "More days", "Sun and
// Moon", CDT", "GMT", and "Show metric". Clicking any of these buttons will recompute just that one pod to display
// different information."
type State struct {
Name string `json:"name"`
Input string `json:"input"`
StepByStep bool `json:"stepbystep"`
ButtonStyle string `json:"buttonstyle"`
}
type SubPod struct {
//Usually an empty string because most subpod elements don't have a title
Title string `json:"title"`
//HTML <img> element
Img Img `json:"img"`
//Textual representation of the subpod
Plaintext string `json:"plaintext"`
}
type Img struct {
Src string `json:"src"`
Alt string `json:"alt"`
Title string `json:"title"`
Width int `json:"width"`
Height int `json:"height"`
Type string `json:"type"`
Themes string `json:"themes"`
ColorInvertable bool `json:"colorinvertable"`
ContentType string `json:"contenttype"`
}
// GetQueryResult gets the query result from the API and returns it.
// Example extra parameter: "format=image", for a url.Value it'd be:
// u := url.Values{}
// u.Add("format", "image")
// Additional information about parameters can be found at
// http://products.wolframalpha.com/docs/WolframAlpha-API-Reference.pdf, page 42
func (c *Client) GetQueryResult(query string, params url.Values) (*Json, error) {
query = url.QueryEscape(query)
url := fmt.Sprintf("https://api.wolframalpha.com/v2/query?input=%s&appid=%s&output=JSON", query, c.AppID)
if params != nil {
url += "&" + params.Encode()
}
data := &Json{}
res, err := http.Get(url)
if err != nil {
return nil, err
}
err = unmarshal(res, data)
return data, err
}
// Gets the json from the API and assigns the data to the target.
// The target being a QueryResult struct
func unmarshal(body *http.Response, target interface{}) error {
defer body.Body.Close()
return json.NewDecoder(body.Body).Decode(target)
}
// GetSimpleQuery gets an image from the `simple` endpoint.
//
// # Returns the image as a response body, the query url, and an error
//
// Can take some extra parameters, e.g `background=F5F5F5`
// sets the background color to #F5F5F5
//
// The rest of the parameters can be found here https://products.wolframalpha.com/simple-api/documentation/
func (c *Client) GetSimpleQuery(query string, params url.Values) (io.ReadCloser, string, error) {
query = url.QueryEscape(query)
query = fmt.Sprintf("http://api.wolframalpha.com/v1/simple?appid=%s&input=%s&output=json", c.AppID, query)
if params != nil {
query += "&" + params.Encode()
}
res, err := http.Get(query)
if err != nil {
return nil, "", err
}
return res.Body, query, err
}
type Unit int
const (
Imperial Unit = iota
Metric
)
func (c *Client) GetShortAnswerQuery(query string, units Unit, timeout int) (string, error) {
query = url.QueryEscape(query)
switch units {
case Imperial:
query += "&units=imperial"
case Metric:
query += "&units=metric"
}
if timeout != 0 {
query += "&timeout=" + strconv.Itoa(timeout)
}
query = fmt.Sprintf("https://api.wolframalpha.com/v1/result?appid=%s&i=%s&output=json", c.AppID, query)
res, err := http.Get(query)
if err != nil {
return "", err
}
defer res.Body.Close()
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
return string(b), nil
}
func (c *Client) GetSpokentAnswerQuery(query string, units Unit, timeout int) (string, error) {
query = url.QueryEscape(query)
switch units {
case Imperial:
query += "&units=imperial"
case Metric:
query += "&units=metric"
}
if timeout != 0 {
query += "&timeout=" + strconv.Itoa(timeout)
}
query = fmt.Sprintf("https://api.wolframalpha.com/v1/spoken?appid=%s&i=%s&output=json", c.AppID, query)
res, err := http.Get(query)
if err != nil {
return "", err
}
defer res.Body.Close()
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return "", err
}
return string(b), nil
}
type Mode int
const (
Default Mode = iota
Voice
)
type FastQueryResult struct {
Version string `json:"version"`
SpellingCorrection string `json:"spellingCorretion"`
BuildNumber string `json:"buildnumber"`
Query []*struct {
I string `json:"i"`
Accepted string `json:"accepted"`
Timing string `json:"timing"`
Domain string `json:"domain"`
ResultSignificanceScore string `json:"resultsignificancescore"`
SummaryBox *struct {
Path string `json:"path"`
} `json:"summarybox"`
} `json:"query"`
}
func (c *Client) GetFastQueryRecognizer(query string, mode Mode) (*FastQueryResult, error) {
query = url.QueryEscape(query)
switch mode {
case Default:
query += "&mode=Default"
case Voice:
query += "&mode=Voice"
}
query = fmt.Sprintf("https://www.wolframalpha.com/queryrecognizer/query.jsp?appid=%s&i=%s&output=json", c.AppID, query)
res, err := http.Get(query)
if err != nil {
return nil, err
}
qres := &FastQueryResult{}
err = unmarshal(res, qres)
if err != nil {
return nil, err
}
return qres, nil
}