A copyright violation detector running on Wikimedia Cloud Services https://tools.wmflabs.org/copyvios/
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 

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