A copyright violation detector running on Wikimedia Cloud Services https://tools.wmflabs.org/copyvios/
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

266 lines
13 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_prev = 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. block = [prev_prev, prev] # Block for before
  101. alock = [prev, sword] # Block for after
  102. before = [block in delta.chain and sword in delta.chain[block]]
  103. after = [alock in delta.chain and next in delta.chain[alock]]
  104. is_first = i == 0
  105. is_last = i + 1 == len(all_words)
  106. res = highlight_word(word, before, after, is_first, is_last)
  107. processed_words.append(res)
  108. prev_prev = prev
  109. prev = sword
  110. processed.append(u" ".join(processed_words))
  111. i += 1
  112. return u"<br /><br />".join(processed)
  113. def highlight_word(word, before, after, is_first, is_last):
  114. if before and after:
  115. # Word is in the middle of a highlighted block, so don't change
  116. # anything unless this is the first word (force block to start) or
  117. # the last word (force block to end):
  118. res = word
  119. if is_first:
  120. res = u'<span class="cv-hl">' + res
  121. if is_last:
  122. res += u'</span>'
  123. elif before:
  124. # Word is the last in a highlighted block, so fade it out and then
  125. # end the block; force open a block before the word if this is the
  126. # first word:
  127. res = fade_word(word, u"out") + u"</span>"
  128. if is_first:
  129. res = u'<span class="cv-hl">' + res
  130. elif after:
  131. # Word is the first in a highlighted block, so start the block and
  132. # then fade it in; force close the block after the word if this is
  133. # the last word:
  134. res = u'<span class="cv-hl">' + fade_word(word, u"in")
  135. if is_last:
  136. res += u"</span>"
  137. else:
  138. # Word is completely outside of a highlighted block, so do nothing:
  139. res = word
  140. return res
  141. def fade_word(word, dir):
  142. if len(word) <= 4:
  143. return u'<span class="cv-hl-{0}">{1}</span>'.format(dir, word)
  144. if dir == u"out":
  145. return u'{0}<span class="cv-hl-out">{1}</span>'.format(word[:-4], word[-4:])
  146. return u'<span class="cv-hl-in">{0}</span>{1}'.format(word[:4], word[4:])
  147. def strip_word(word):
  148. return sub("[^\w\s-]", "", word.lower(), flags=UNICODE)
  149. def urlstrip(url):
  150. if url.startswith("http://"):
  151. url = url[7:]
  152. if url.startswith("https://"):
  153. url = url[8:]
  154. if url.startswith("www."):
  155. url = url[4:]
  156. if url.endswith("/"):
  157. url = url[:-1]
  158. return url
  159. %>\
  160. <%
  161. query = parse_qs(environ["QUERY_STRING"])
  162. try:
  163. lang = query["lang"][0]
  164. project = query["project"][0]
  165. title = query["title"][0]
  166. except (KeyError, IndexError):
  167. page = None
  168. else:
  169. page, result = get_results(lang, project, title, query)
  170. %>\
  171. <%include file="/support/header.mako" args="environ=environ, title='Copyvio Detector', add_css=('copyvios.css',), add_js=('copyvios.js',)"/>
  172. <h1>Copyvio Detector</h1>
  173. <p>This tool attempts to detect <a href="//en.wikipedia.org/wiki/WP:COPYVIO">copyright violations</a> in Wikipedia articles.</p>
  174. <form action="${environ['PATH_INFO']}" method="get">
  175. <table>
  176. <tr>
  177. <td>Site:</td>
  178. <td>
  179. <select name="lang">
  180. <option value="en" selected="selected">en (English)</option>
  181. </select>
  182. <select name="project">
  183. <option value="wikipedia" selected="selected">Wikipedia</option>
  184. </select>
  185. </td>
  186. </tr>
  187. <tr>
  188. <td>Page title:</td>
  189. % if page:
  190. <td><input type="text" name="title" size="50" value="${page.title() | h}" /></td>
  191. % else:
  192. <td><input type="text" name="title" size="50" /></td>
  193. % endif
  194. </tr>
  195. % if query.get("nocache") or page:
  196. <tr>
  197. <td>Bypass cache:</td>
  198. % if query.get("nocache"):
  199. <td><input type="checkbox" name="nocache" value="1" checked="checked" /></td>
  200. % else:
  201. <td><input type="checkbox" name="nocache" value="1" /></td>
  202. % endif
  203. </tr>
  204. % endif
  205. <tr>
  206. <td><button type="submit">Submit</button></td>
  207. </tr>
  208. </table>
  209. </form>
  210. % if page:
  211. <div class="divider"></div>
  212. <div id="cv-result-${'yes' if result.violation else 'no'}">
  213. % if result.violation:
  214. <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>
  215. % else:
  216. <h2 id="cv-result-header">No violations detected in <a href="${page.url()}">${page.title() | h}</a>.</h2>
  217. % endif
  218. <ul id="cv-result-list">
  219. <li><b><tt>${round(result.confidence * 100, 1)}%</tt></b> confidence of a violation.</li>
  220. % if result.cached:
  221. <li>Results are <a id="cv-cached" href="#">cached
  222. <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>
  223. </a> from ${result.cache_time} (${result.cache_age} ago). <a href="${environ['REQUEST_URI'] | h}&amp;nocache=1">Bypass the cache.</a></li>
  224. % else:
  225. <li>Results generated in <tt>${round(result.tdiff, 3)}</tt> seconds using <tt>${result.queries}</tt> queries.</li>
  226. % endif
  227. <li><a id="cv-result-detail-link" href="#cv-result-detail" onclick="copyvio_toggle_details()">Show details:</a></li>
  228. </ul>
  229. <div id="cv-result-detail" style="display: none;">
  230. <ul id="cv-result-detail-list">
  231. <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>
  232. % if result.cached:
  233. % if result.queries:
  234. <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>
  235. % else:
  236. <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>
  237. % endif
  238. % endif
  239. <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>
  240. </ul>
  241. <table id="cv-chain-table">
  242. <tr>
  243. <td>Article: <div class="cv-chain-detail"><p>${highlight_delta(result.article_chain, result.delta_chain)}</p></div></td>
  244. <td>Source: <div class="cv-chain-detail"><p>${highlight_delta(result.source_chain, result.delta_chain)}</p></div></td>
  245. </tr>
  246. </table>
  247. </div>
  248. </div>
  249. % endif
  250. <%include file="/support/footer.mako" args="environ=environ"/>