forked from Unthinkingbit/charity
/
devtome.py
354 lines (312 loc) · 14.3 KB
/
devtome.py
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
"""
<textarea id="wpTextbox1" name="wpTextbox1" cols="80" rows="25" readonly="">==Articles==
===Collated===
*[[Home Remedy]] - Source: [http://en.wikibooks.org/wiki/Ethnomedicine/Ethnomedicine_by_Illness Ethnomedicine by Illness] and [http://en.wikibooks.org/wiki/Ethnomedicine/Home_Remedies Home Remedies] - Improvement: Combined wikibooks with wikipedia articles
===Original===
*[[Devcoin]] - Source: [https://github.com/Unthinkingbit/charity/blob/master/devcoin.html https://github.com/Unthinkingbit/charity/blob/master/devcoin.html]
*[[Devcoin_bounty|Devcoin Bounty]] - Source: [https://github.com/Unthinkingbit/charity/blob/master/devcoin_bounty.html https://github.com/Unthinkingbit/charity/blob/master/devcoin_bounty.html]
==Tip==
Coin Address: 17vec4jQGCzMEsTnivizHPaowE715tu2CB</textarea>
Account is a program to generate a devcoin receiver file from a bitcoinshare, bounty, devcoinshare and peer file.
This is meant to be used by devcoin accountants and auditors to create and check the receiver files. The account file has a list of addresses and shares. Anything after a dash is a comment.
==Commands==
===Help===
The -h option, the -help option, will print the help, which is this document. The example follows:
python account.py -h
===Input===
Default is https://raw.github.com/Unthinkingbit/charity/master/account_3.csv
The -input option sets the input file name. The example follows:
python account.py -input https://raw.github.com/Unthinkingbit/charity/master/account_3.csv
An example of an account information input file is at:
https://raw.github.com/Unthinkingbit/charity/master/account_3.csv
===Output===
Default is test_receiver.csv
The -output option sets the output. If the output ends with stderr, the output will be sent to stderr If the output ends with stdout, the output will be sent to stdout. If the output does not end with stderr or stdout, the output will be written to a file by that name, with whatever suffix the input file has. The example follows:
python genereceiver.py -output test_receiver.csv
An example of an genereceiver output file is at:
https://raw.github.com/Unthinkingbit/charity/master/test_receiver_3.csv
==Install==
For genereceiver to run, you need Python 2.x, almoner will probably not run with python 3.x. To check if it is on your machine, in a terminal type:
python
If python 2.x is not on your machine, download the latest python 2.x, which is available from:
http://www.python.org/download/
"""
from datetime import date
import almoner
import cStringIO
import math
import os
import shutil
import sys
import time
__license__ = 'MIT'
def addJoinedTitles(cString, words):
'Add joined titles to the cString.'
words.append('Collated Word Count')
words.append('Collated Weighted Word Count')
words.append('Image Count')
words.append('Original Word Count')
words.append('Word Count')
words.append('Weighted Word Count')
words.append('Cumulative Payout')
words.append('Proportion')
words.append('Previous Cumulative Payout')
words.append('Payout')
cString.write('%s\n' % ','.join(words))
def getAuthors(backupFolder, lines, titles):
'Get the authors.'
authors = []
almoner.makeDirectory(backupFolder)
for line in lines[1 :]:
words = line.split(',')
if len(words) > 0:
if len(words[0]) > 0:
authors.append(Author(backupFolder, titles, words))
almoner.writeZipFileByFolder(backupFolder)
return authors
def getEarningsText(authors):
'Get the devtome earnings text.'
cString = cStringIO.StringIO()
for author in authors:
coinAddress = author.parameterDictionary['Coin Address']
name = author.parameterDictionary['Name']
lastPayoutString = str(author.tomecount.payout)
if lastPayoutString != '0':
cString.write('%s,%s,%s-Word Count(%s)\n' % (name, coinAddress, lastPayoutString, author.sourceAddress.replace('&do=edit', '')))
return cString.getvalue()
def getImageCount(linkText):
'Get the image count of the page linked to in the line.'
if linkText == '':
return 0
imageCount = 0
lines = linkText.lower().split('[[')
for line in lines:
if line.startswith('file:') or line.startswith('image:'):
if (']]') in line:
line = line[: line.find(']]')].strip()
if ('|') in line:
line = line[: line.find('|')].strip()
if line.endswith('.gif') or line.endswith('.jpg') or line.endswith('.png'):
imageCount += 1
return imageCount
def getLinkName(line):
'Get the name of the article in the line.'
linkStartIndex = line.find('[[')
if linkStartIndex == -1:
return ''
linkStartIndex += len('[[')
linkEndIndex = line.find(']]', linkStartIndex)
if linkEndIndex == -1:
return ''
linkString = line[linkStartIndex : linkEndIndex]
linkDividerIndex = linkString.find('|')
if linkDividerIndex != -1:
linkString = linkString[: linkDividerIndex]
return linkString
def getLinkText(line):
'Get the text of the page linked to in the line.'
linkString = getLinkName(line)
if linkString == '':
return ''
time.sleep(1)
return getSourceText('http://devtome.com/doku.php?id=%s&do=edit' % linkString)
def getSourceText(address):
'Get the devtome source text for the address.'
text = almoner.getInternetText(address)
textAreaTagIndex = text.find('<textarea')
if textAreaTagIndex == -1:
print('')
print('Warning, no textarea tag found for:')
print(address)
print('')
return ''
tagEndIndex = text.find('>', textAreaTagIndex)
if tagEndIndex == -1:
print('')
print('Warning, no tag end found for:')
print(address)
print('')
return ''
textAreaEndTagIndex = text.find('</textarea>', tagEndIndex)
if textAreaEndTagIndex == -1:
print('')
print('Warning, no textarea end tag found for:')
print(address)
print('')
return ''
return text[tagEndIndex + 1 : textAreaEndTagIndex].lstrip()
def getSummaryText(earningsText, round, totalTomecount):
'Get the summary text.'
cString = cStringIO.StringIO()
cString.write('The round %s devtome word earnings are pasted below and at:\n' % round)
cString.write('https://raw.github.com/Unthinkingbit/charity/master/devtome_earnings_%s.csv\n\n' % round)
cString.write('%s\n' % earningsText)
cString.write('They are generated by devtome.py:\n')
cString.write('https://raw.github.com/Unthinkingbit/charity/master/devtome.py\n\n')
cString.write('The word counts for each writer are at:\n')
cString.write('https://raw.github.com/Unthinkingbit/charity/master/devtome_%s.csv\n\n' % round)
cString.write('The word earnings were generated on %s, and the total word counts follow below.\n\n' % date.today().isoformat())
cString.write('Collated Word Count: %s\n' % almoner.getCommaNumberString(totalTomecount.collatedWordCount))
cString.write('Collated Weighted Word Count: %s\n' % almoner.getCommaNumberString(totalTomecount.collatedWeightedWordCount))
cString.write('Images: %s\n' % almoner.getCommaNumberString(totalTomecount.imageCount))
cString.write('Original Word Count: %s\n' % almoner.getCommaNumberString(totalTomecount.originalWordCount))
cString.write('Total Word Count: %s\n' % almoner.getCommaNumberString(totalTomecount.wordCount))
cString.write('Total Weighted Word Count: %s\n' % almoner.getCommaNumberString(totalTomecount.weightedWordCount))
return cString.getvalue()
def getTomecountText(authors, totalTomecount):
'Get the tomecount csv text for the authors.'
cString = cStringIO.StringIO()
addJoinedTitles(cString, ['Name','Coin Address'])
weightedWordCountFloat = float(totalTomecount.weightedWordCount)
for author in authors:
author.tomecount.proportion = float(author.tomecount.weightedWordCount) / weightedWordCountFloat
author.addLine(cString)
addJoinedTitles(cString, ['','Totals'])
cString.write(totalTomecount.getJoinedWords(['','']))
cString.write(',Date\n')
cString.write(',%s\n' % date.today().isoformat())
return cString.getvalue()
def getTotalTomecount(authors):
'Get the tomecount csv text for the authors.'
totalTomecount = Tomecount()
totalTomecount.proportion = 1.0
for author in authors:
totalTomecount.collatedWordCount += author.tomecount.collatedWordCount
totalTomecount.collatedWeightedWordCount += author.tomecount.collatedWeightedWordCount
totalTomecount.imageCount += author.tomecount.imageCount
totalTomecount.originalWordCount += author.tomecount.originalWordCount
totalTomecount.wordCount += author.tomecount.wordCount
totalTomecount.weightedWordCount += author.tomecount.weightedWordCount
totalTomecount.cumulativePayout += author.tomecount.cumulativePayout
totalTomecount.payout += author.tomecount.payout
totalTomecount.previousPayout += author.tomecount.previousPayout
return totalTomecount
def getWordCount(linkText):
'Get the word count of the page linked to in the line.'
if linkText == '':
return 0
linkText = linkText.replace('.', ' ').replace(',', ' ').replace(';', ' ').replace('\n', ' ').replace('\r', ' ').replace('\t', ' ')
return len(linkText.split())
def writeOutput(arguments):
'Write output.'
if '-h' in arguments or '-help' in arguments:
print(__doc__)
return
round = int(almoner.getParameter(arguments, '23', 'round'))
rootFileName = almoner.getParameter(arguments, 'devtome', 'wiki')
currentFileName = almoner.getParameter(arguments, rootFileName + '_%s.csv' % round, 'current')
previousFileName = almoner.getParameter(arguments, rootFileName + '_%s.csv' % (round - 1), 'previous')
lines = almoner.getTextLines(almoner.getFileText(previousFileName))
titleLine = lines[0]
titles = titleLine.split(',')
backupFolder = rootFileName + '_articles'
authors = getAuthors(backupFolder, lines, titles)
totalTomecount = getTotalTomecount(authors)
tomecountText = getTomecountText(authors, totalTomecount)
earningsText = getEarningsText(authors)
outputSummaryTo = almoner.getParameter(arguments, 'devtome_summary.txt', 'summary')
almoner.writeFileText(currentFileName, tomecountText)
outputEarningsTo = almoner.getParameter(arguments, 'devtome_earnings_%s.csv' % round, 'earnings')
if almoner.sendOutputTo(outputEarningsTo, earningsText):
print('The devtome earnings file has been written to:\n%s\n' % outputEarningsTo)
if almoner.sendOutputTo(outputSummaryTo, getSummaryText(earningsText, round, totalTomecount)):
print('The summary file has been written to:\n%s\n' % outputSummaryTo)
class Author:
'A class to handle an author.'
def __init__(self, backupFolder, titles, words):
'Initialize.'
self.tomecount = Tomecount()
self.parameterDictionary = {}
for wordIndex, word in enumerate(words):
self.parameterDictionary[titles[wordIndex]] = word
if 'Cumulative Payout' in self.parameterDictionary:
self.tomecount.previousPayout = int(self.parameterDictionary['Cumulative Payout'])
name = self.parameterDictionary['Name']
self.sourceAddress = 'http://devtome.com/doku.php?id=wiki:user:%s&do=edit' % name
print('Loading articles from %s' % name)
sourceText = getSourceText(self.sourceAddress)
almoner.writeFileText(os.path.join(backupFolder, 'wiki:user:' + name), sourceText)
isCollated = False
isOriginal = False
for line in almoner.getTextLines(sourceText):
lineStrippedLower = line.strip().lower()
if '==' in lineStrippedLower:
isCollated = False
isOriginal = False
if 'collated' in lineStrippedLower:
isCollated = True
elif 'original' in lineStrippedLower:
isOriginal = True
if isCollated:
linkText = getLinkText(lineStrippedLower)
self.tomecount.imageCount += getImageCount(linkText)
wordCount = getWordCount(linkText)
self.tomecount.collatedWordCount += wordCount
if wordCount > 0:
print('Collated article: %s, Word Count: %s' % (lineStrippedLower, almoner.getCommaNumberString(wordCount)))
almoner.writeFileText(os.path.join(backupFolder, getLinkName(lineStrippedLower)[1 :]), linkText)
if isOriginal:
linkText = getLinkText(lineStrippedLower)
self.tomecount.imageCount += getImageCount(linkText)
wordCount = getWordCount(linkText)
self.tomecount.originalWordCount += wordCount
if wordCount > 0:
print('Original article: %s, Word Count: %s' % (lineStrippedLower, almoner.getCommaNumberString(wordCount)))
almoner.writeFileText(os.path.join(backupFolder, getLinkName(lineStrippedLower)[1 :]), linkText)
self.tomecount.collatedWeightedWordCount = self.tomecount.collatedWordCount * 3 / 10
self.tomecount.wordCount = self.tomecount.collatedWordCount + self.tomecount.originalWordCount
self.tomecount.weightedWordCount = self.tomecount.collatedWeightedWordCount + self.tomecount.originalWordCount
self.tomecount.weightedWordCount += 10 * self.tomecount.imageCount
if self.tomecount.weightedWordCount >= 1000:
self.tomecount.cumulativePayout = int(round(float(self.tomecount.weightedWordCount) * 0.001))
print('Weighted Word Count: %s' % almoner.getCommaNumberString(self.tomecount.weightedWordCount))
self.tomecount.payout = max(self.tomecount.cumulativePayout - self.tomecount.previousPayout, 0)
maximumPayout = 80
if self.tomecount.payout > maximumPayout:
self.tomecount.payout = maximumPayout
self.tomecount.cumulativePayout = self.tomecount.previousPayout + maximumPayout
def __repr__(self):
'Get the string representation of this class.'
return str(self.parameterDictionary)
def addLine(self, cString):
'Add the author to the tomecount csv cString.'
words = [self.parameterDictionary['Name'], self.parameterDictionary['Coin Address']]
if self.tomecount.weightedWordCount == 0 and self.tomecount.previousPayout == 0:
cString.write('%s\n' % ','.join(words))
return
cString.write(self.tomecount.getJoinedWords(words))
class Tomecount:
'A class to handle the tome accounting.'
def __init__(self):
'Initialize.'
self.collatedWordCount = 0
self.imageCount = 0
self.originalWordCount = 0
self.collatedWeightedWordCount = 0
self.payout = 0
self.previousPayout = 0
self.proportion = 0.0
self.wordCount = 0
self.weightedWordCount = 0
self.cumulativePayout = 0
def __repr__(self):
'Get the string representation of this class.'
return self.getJoinedWords([])
def getJoinedWords(self, words):
'Add the variables to the words.'
words.append(str(self.collatedWordCount))
words.append(str(self.collatedWeightedWordCount))
words.append(str(self.imageCount))
words.append(str(self.originalWordCount))
words.append(str(self.wordCount))
words.append(str(self.weightedWordCount))
words.append(str(self.cumulativePayout))
words.append(str(self.proportion))
words.append(str(self.previousPayout))
words.append(str(self.payout))
return '%s\n' % ','.join(words)
def main():
'Write output.'
writeOutput(sys.argv)
if __name__ == '__main__':
main()