A copyright violation detector running on Wikimedia Cloud Services https://tools.wmflabs.org/copyvios/
No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 

263 líneas
12 KiB

  1. <%!
  2. from collections import defaultdict
  3. from datetime import datetime
  4. from hashlib import sha256
  5. from itertools import count
  6. from os.path import expanduser
  7. from re import sub, UNICODE
  8. from sys import path
  9. from time import time
  10. from urlparse import parse_qs
  11. from earwigbot import bot, exceptions
  12. import oursql
  13. def get_results(lang, project, title, query):
  14. bot = bot.Bot(".earwigbot")
  15. try:
  16. site = bot.wiki.get_site(lang=lang, project=project)
  17. except exceptions.SiteNotFoundError:
  18. try:
  19. site = bot.wiki.add_site(lang=lang, project=project)
  20. except exceptions.APIError:
  21. return None, None
  22. page = site.get_page(title)
  23. conn = open_sql_connection(bot)
  24. if not query.get("nocache"):
  25. result = get_cached_results(page, conn)
  26. if query.get("nocache") or not result:
  27. result = get_fresh_results(page, conn)
  28. return page, result
  29. def open_sql_connection(bot):
  30. conn_args = bot.config.wiki["_toolserverSQLCache"]
  31. if "read_default_file" not in conn_args and "user" not in conn_args and "passwd" not in conn_args:
  32. conn_args["read_default_file"] = expanduser("~/.my.cnf")
  33. if "autoping" not in conn_args:
  34. conn_args["autoping"] = True
  35. if "autoreconnect" not in conn_args:
  36. conn_args["autoreconnect"] = True
  37. return oursql.connect(**conn_args)
  38. def get_cached_results(page, conn):
  39. query1 = "DELETE FROM cache WHERE cache_time < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 1 DAY)"
  40. query2 = "SELECT cache_url, cache_time, cache_queries, cache_process_time FROM cache WHERE cache_id = ? AND cache_hash = ?"
  41. pageid = page.pageid()
  42. hash = sha256(page.get()).hexdigest()
  43. t_start = time()
  44. with conn.cursor() as cursor:
  45. cursor.execute(query1)
  46. cursor.execute(query2, (pageid, hash))
  47. results = cursor.fetchall()
  48. if not results:
  49. return None
  50. url, cache_time, num_queries, original_tdiff = results[0]
  51. result = page.copyvio_compare(url)
  52. result.cached = True
  53. result.queries = num_queries
  54. result.tdiff = time() - t_start
  55. result.original_tdiff = original_tdiff
  56. result.cache_time = cache_time.strftime("%b %d, %Y %H:%M:%S UTC")
  57. result.cache_age = format_date(cache_time)
  58. return result
  59. def format_date(cache_time):
  60. diff = datetime.utcnow() - cache_time
  61. if diff.seconds > 3600:
  62. return "{0} hours".format(diff.seconds / 3600)
  63. if diff.seconds > 60:
  64. return "{0} minutes".format(diff.seconds / 60)
  65. return "{0} seconds".format(diff.seconds)
  66. def get_fresh_results(page, conn):
  67. t_start = time()
  68. result = page.copyvio_check(max_queries=10)
  69. result.cached = False
  70. result.tdiff = time() - t_start
  71. cache_result(page, result, conn)
  72. return result
  73. def cache_result(page, result, conn):
  74. pageid = page.pageid()
  75. hash = sha256(page.get()).hexdigest()
  76. query1 = "SELECT 1 FROM cache WHERE cache_id = ?"
  77. query2 = "DELETE FROM cache WHERE cache_id = ?"
  78. query3 = "INSERT INTO cache VALUES (?, ?, ?, CURRENT_TIMESTAMP, ?, ?)"
  79. with conn.cursor() as cursor:
  80. cursor.execute(query1, (pageid,))
  81. if cursor.fetchall():
  82. cursor.execute(query2, (pageid,))
  83. cursor.execute(query3, (pageid, hash, result.url, result.queries,
  84. result.tdiff))
  85. def highlight_delta(chain, delta):
  86. processed = []
  87. prev = chain.START
  88. i = 0
  89. all_words = chain.text.split()
  90. paragraphs = chain.text.split("\n")
  91. for paragraph in paragraphs:
  92. processed_words = []
  93. words = paragraph.split(" ")
  94. for word, i in zip(words, count(i)):
  95. try:
  96. next = strip_word(all_words[i+1])
  97. except IndexError:
  98. next = chain.END
  99. sword = strip_word(word)
  100. before = prev in delta.chain and sword in delta.chain[prev]
  101. after = sword in delta.chain and next in delta.chain[sword]
  102. is_first = i == 0
  103. is_last = i + 1 == len(all_words)
  104. res = highlight_word(word, before, after, is_first, is_last)
  105. processed_words.append(res)
  106. prev = sword
  107. processed.append(u" ".join(processed_words))
  108. i += 1
  109. return u"<br /><br />".join(processed)
  110. def highlight_word(word, before, after, is_first, is_last):
  111. if before and after:
  112. # Word is in the middle of a highlighted block, so don't change
  113. # anything unless this is the first word (force block to start) or
  114. # the last word (force block to end):
  115. res = word
  116. if is_first:
  117. res = u'<span class="cv-hl">' + res
  118. if is_last:
  119. res += u'</span>'
  120. elif before:
  121. # Word is the last in a highlighted block, so fade it out and then
  122. # end the block; force open a block before the word if this is the
  123. # first word:
  124. res = fade_word(word, u"out") + u"</span>"
  125. if is_first:
  126. res = u'<span class="cv-hl">' + res
  127. elif after:
  128. # Word is the first in a highlighted block, so start the block and
  129. # then fade it in; force close the block after the word if this is
  130. # the last word:
  131. res = u'<span class="cv-hl">' + fade_word(word, u"in")
  132. if is_last:
  133. res += u"</span>"
  134. else:
  135. # Word is completely outside of a highlighted block, so do nothing:
  136. res = word
  137. return res
  138. def fade_word(word, dir):
  139. if len(word) <= 4:
  140. return u'<span class="cv-hl-{0}">{1}</span>'.format(dir, word)
  141. if dir == u"out":
  142. return u'{0}<span class="cv-hl-out">{1}</span>'.format(word[:-4], word[-4:])
  143. return u'<span class="cv-hl-in">{0}</span>{1}'.format(word[:4], word[4:])
  144. def strip_word(word):
  145. return sub("[^\w\s-]", "", word.lower(), flags=UNICODE)
  146. def urlstrip(url):
  147. if url.startswith("http://"):
  148. url = url[7:]
  149. if url.startswith("https://"):
  150. url = url[8:]
  151. if url.startswith("www."):
  152. url = url[4:]
  153. if url.endswith("/"):
  154. url = url[:-1]
  155. return url
  156. %>\
  157. <%
  158. query = parse_qs(environ["QUERY_STRING"])
  159. try:
  160. lang = query["lang"][0]
  161. project = query["project"][0]
  162. title = query["title"][0]
  163. except (KeyError, IndexError):
  164. page = None
  165. else:
  166. page, result = get_results(lang, project, title, query)
  167. %>\
  168. <%include file="/support/header.mako" args="environ=environ, title='Copyvio Detector', add_css=('copyvios.css',), add_js=('copyvios.js',)"/>
  169. <h1>Copyvio Detector</h1>
  170. <p>This tool attempts to detect <a href="//en.wikipedia.org/wiki/WP:COPYVIO">copyright violations</a> in Wikipedia articles.</p>
  171. <form action="${environ['PATH_INFO']}" method="get">
  172. <table>
  173. <tr>
  174. <td>Site:</td>
  175. <td>
  176. <select name="lang">
  177. <option value="en" selected="selected">en (English)</option>
  178. </select>
  179. <select name="project">
  180. <option value="wikipedia" selected="selected">Wikipedia</option>
  181. </select>
  182. </td>
  183. </tr>
  184. <tr>
  185. <td>Page title:</td>
  186. % if page:
  187. <td><input type="text" name="title" size="50" value="${page.title() | h}" /></td>
  188. % else:
  189. <td><input type="text" name="title" size="50" /></td>
  190. % endif
  191. </tr>
  192. % if query.get("nocache") or page:
  193. <tr>
  194. <td>Bypass cache:</td>
  195. % if query.get("nocache"):
  196. <td><input type="checkbox" name="nocache" value="1" checked="checked" /></td>
  197. % else:
  198. <td><input type="checkbox" name="nocache" value="1" /></td>
  199. % endif
  200. </tr>
  201. % endif
  202. <tr>
  203. <td><button type="submit">Submit</button></td>
  204. </tr>
  205. </table>
  206. </form>
  207. % if page:
  208. <div class="divider"></div>
  209. <div id="cv-result-${'yes' if result.violation else 'no'}">
  210. % if result.violation:
  211. <h2 id="cv-result-header"><a href="${page.url()}">${page.title() | h}</a> is a suspected violation of <a href="${result.url | h}">${result.url | urlstrip}</a>.</h2>
  212. % else:
  213. <h2 id="cv-result-header">No violations detected in <a href="${page.url()}">${page.title() | h}</a>.</h2>
  214. % endif
  215. <ul id="cv-result-list">
  216. <li><b><tt>${round(result.confidence * 100, 1)}%</tt></b> confidence of a violation.</li>
  217. % if result.cached:
  218. <li>Results are <a id="cv-cached" href="#">cached
  219. <span>To save time (and money), this tool will retain the results of checks for up to 24 hours. This includes the URL of the "violated" source, but neither its content nor the content of the article. Future checks on the same page (assuming it remains unchanged) will not involve additional search queries, but a fresh comparison against the source URL will be made.</span>
  220. </a> from ${result.cache_time} (${result.cache_age} ago). <a href="${environ['REQUEST_URI'] | h}&amp;nocache=1">Bypass the cache.</a></li>
  221. % else:
  222. <li>Results generated in <tt>${round(result.tdiff, 3)}</tt> seconds using <tt>${result.queries}</tt> queries.</li>
  223. % endif
  224. <li><a id="cv-result-detail-link" href="#cv-result-detail" onclick="copyvio_toggle_details()">Show details:</a></li>
  225. </ul>
  226. <div id="cv-result-detail" style="display: none;">
  227. <ul id="cv-result-detail-list">
  228. <li>Markov chain size: Article: <tt>${result.article_chain.size()}</tt> / Source: <tt>${result.source_chain.size()}</tt> / Delta: <tt>${result.delta_chain.size()}</tt></li>
  229. % if result.cached:
  230. % if result.queries:
  231. <li>Retrieved from cache in <tt>${round(result.tdiff, 3)}</tt> seconds (originally generated in <tt>${round(result.original_tdiff, 3)}</tt>s using <tt>${result.queries}</tt> queries; <tt>${round(result.original_tdiff - result.tdiff, 3)}</tt>s saved).</li>
  232. % else:
  233. <li>Retrieved from cache in <tt>${round(result.tdiff, 3)}</tt> seconds (originally generated in <tt>${round(result.original_tdiff, 3)}</tt>s; <tt>${round(result.original_tdiff - result.tdiff, 3)}</tt>s saved).</li>
  234. % endif
  235. % endif
  236. <li><i>Fun fact:</i> The Wikimedia Foundation paid Yahoo! Inc. <a href="http://info.yahoo.com/legal/us/yahoo/search/bosspricing/details.html">$${result.queries * 0.0008} USD</a> for these results.</li>
  237. </ul>
  238. <table id="cv-chain-table">
  239. <tr>
  240. <td>Article: <div class="cv-chain-detail"><p>${highlight_delta(result.article_chain, result.delta_chain)}</p></div></td>
  241. <td>Source: <div class="cv-chain-detail"><p>${highlight_delta(result.source_chain, result.delta_chain)}</p></div></td>
  242. </tr>
  243. </table>
  244. </div>
  245. </div>
  246. % endif
  247. <%include file="/support/footer.mako" args="environ=environ"/>