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.
 
 
 
 
 

354 lines
17 KiB

  1. <%!
  2. from datetime import datetime
  3. from hashlib import sha256
  4. from itertools import count
  5. from os.path import expanduser
  6. from re import sub, UNICODE
  7. from sys import path
  8. from time import time
  9. from urlparse import parse_qs
  10. from earwigbot import bot, exceptions
  11. import oursql
  12. def get_results(bot, lang, project, title, url, query):
  13. try:
  14. site = bot.wiki.get_site(lang=lang, project=project)
  15. except exceptions.SiteNotFoundError:
  16. try:
  17. site = bot.wiki.add_site(lang=lang, project=project)
  18. except exceptions.APIError:
  19. return None, None
  20. page = site.get_page(title) # TODO: what if the page doesn't exist?
  21. # if url:
  22. # result = get_url_specific_results(page, url)
  23. # else:
  24. # conn = open_sql_connection(bot, "copyvioCache")
  25. # if not query.get("nocache"):
  26. # result = get_cached_results(page, conn)
  27. # if query.get("nocache") or not result:
  28. # result = get_fresh_results(page, conn)
  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 get_url_specific_results(page, url):
  36. t_start = time()
  37. result = page.copyvio_compare(url)
  38. result.tdiff = time() - t_start
  39. return result
  40. def open_sql_connection(bot, dbname):
  41. conn_args = bot.config.wiki["_toolserverSQL"][dbname]
  42. if "read_default_file" not in conn_args and "user" not in conn_args and "passwd" not in conn_args:
  43. conn_args["read_default_file"] = expanduser("~/.my.cnf")
  44. if "autoping" not in conn_args:
  45. conn_args["autoping"] = True
  46. if "autoreconnect" not in conn_args:
  47. conn_args["autoreconnect"] = True
  48. return oursql.connect(**conn_args)
  49. def get_cached_results(page, conn):
  50. query1 = "DELETE FROM cache WHERE cache_time < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 3 DAY)"
  51. query2 = "SELECT cache_url, cache_time, cache_queries, cache_process_time FROM cache WHERE cache_id = ? AND cache_hash = ?"
  52. pageid = page.pageid()
  53. hash = sha256(page.get()).hexdigest()
  54. t_start = time()
  55. with conn.cursor() as cursor:
  56. cursor.execute(query1)
  57. cursor.execute(query2, (pageid, hash))
  58. results = cursor.fetchall()
  59. if not results:
  60. return None
  61. url, cache_time, num_queries, original_tdiff = results[0]
  62. result = page.copyvio_compare(url)
  63. result.cached = True
  64. result.queries = num_queries
  65. result.tdiff = time() - t_start
  66. result.original_tdiff = original_tdiff
  67. result.cache_time = cache_time.strftime("%b %d, %Y %H:%M:%S UTC")
  68. result.cache_age = format_date(cache_time)
  69. return result
  70. def format_date(cache_time):
  71. diff = datetime.utcnow() - cache_time
  72. if diff.seconds > 3600:
  73. return "{0} hours".format(diff.seconds / 3600)
  74. if diff.seconds > 60:
  75. return "{0} minutes".format(diff.seconds / 60)
  76. return "{0} seconds".format(diff.seconds)
  77. def get_fresh_results(page, conn):
  78. t_start = time()
  79. result = page.copyvio_check(max_queries=10)
  80. result.cached = False
  81. result.tdiff = time() - t_start
  82. cache_result(page, result, conn)
  83. return result
  84. def cache_result(page, result, conn):
  85. pageid = page.pageid()
  86. hash = sha256(page.get()).hexdigest()
  87. query1 = "SELECT 1 FROM cache WHERE cache_id = ?"
  88. query2 = "DELETE FROM cache WHERE cache_id = ?"
  89. query3 = "INSERT INTO cache VALUES (?, ?, ?, CURRENT_TIMESTAMP, ?, ?)"
  90. with conn.cursor() as cursor:
  91. cursor.execute(query1, (pageid,))
  92. if cursor.fetchall():
  93. cursor.execute(query2, (pageid,))
  94. cursor.execute(query3, (pageid, hash, result.url, result.queries,
  95. result.tdiff))
  96. def get_sites(bot):
  97. max_staleness = 60 * 60 * 24 * 7
  98. site = bot.wiki.get_site()
  99. conn = open_sql_connection(site, "globals")
  100. query1 = "SELECT update_time FROM updates WHERE update_service = ?"
  101. query2 = "SELECT lang_code, lang_name FROM languages"
  102. query3 = "SELECT project_name FROM projects"
  103. tl_normal = '<option value="{0}">{1}</option>'
  104. tl_select = '<option value="{0}" selected="selected">{1}</option>'
  105. with conn.cursor() as cursor:
  106. cursor.execute(query1, ("sites",))
  107. time_since_update = int(time() - cursor.fetchall()[0][0])
  108. if time_since_update > max_staleness:
  109. update_sites(bot, cursor)
  110. cursor.execute(query2)
  111. langs = []
  112. for lang, lang_name in cursor.fetchall():
  113. template = tl_select if lang == site.lang else tl_normal
  114. fullname = "{0} ({1})".format(lang, lang_name)
  115. langs.append(template.format(lang, fullname))
  116. cursor.execute(query3)
  117. projects = []
  118. for (project,) in cursor.fetchall():
  119. template = tl_select if project == site.project else tl_normal
  120. projects.append(template.format(project, project.capitalize()))
  121. langs = "\n".join(langs)
  122. projects = "\n".join(projects)
  123. result = '<select name="lang">\n{0}\n</select>\n'.format(langs)
  124. result += '<select name="project">\n{0}\n</select>'.format(projects)
  125. return result
  126. def update_sites(site, cursor):
  127. matrix = site.api_query(action="sitematrix")["sitematrix"]
  128. del matrix["count"]
  129. languages, projects = set(), set()
  130. for site in matrix.itervalues():
  131. if isinstance(site, list): # Special sites
  132. continue
  133. code = site["code"].encode("utf8")
  134. name = site["name"].encode("utf8")
  135. languages.add((code, name))
  136. for web in site["site"]:
  137. project = "wikipedia" if web["code"] == "wiki" else web["code"]
  138. projects.add(project)
  139. save_site_updates(cursor, languages, projects)
  140. def save_site_updates(cursor, languages, projects):
  141. query1 = "SELECT lang_code, lang_name FROM languages"
  142. query2 = "DELETE FROM languages WHERE lang_code = ? AND lang_name = ?"
  143. query3 = "INSERT INTO languages VALUES (?, ?)"
  144. query4 = "SELECT project_name FROM projects"
  145. query5 = "DELETE FROM projects WHERE project_name = ?"
  146. query6 = "INSERT INTO projects VALUES (?)"
  147. query7 = "UPDATE updates SET update_time = ? WHERE update_service = ?"
  148. synchronize_sites_with_db(cursor, languages, query1, query2, query3)
  149. synchronize_sites_with_db(cursor, projects, query4, query5, query6)
  150. cursor.execute(query7, (time(), "sites"))
  151. def synchronize_sites_with_db(cursor, updates, q_list, q_rmv, q_update):
  152. removals = []
  153. for site in cursor.execute(q_list):
  154. updates.remove(site) if site in updates else removals.append(site)
  155. cursor.executemany(q_rmv, removals)
  156. cursor.executemany(q_update, updates)
  157. def highlight_delta(chain, delta):
  158. processed = []
  159. prev_prev = prev = chain.START
  160. i = 0
  161. all_words = chain.text.split()
  162. paragraphs = chain.text.split("\n")
  163. for paragraph in paragraphs:
  164. processed_words = []
  165. words = paragraph.split(" ")
  166. for word, i in zip(words, count(i)):
  167. try:
  168. next = strip_word(all_words[i+1])
  169. except IndexError:
  170. next = chain.END
  171. sword = strip_word(word)
  172. block = [prev_prev, prev] # Block for before
  173. alock = [prev, sword] # Block for after
  174. before = [block in delta.chain and sword in delta.chain[block]]
  175. after = [alock in delta.chain and next in delta.chain[alock]]
  176. is_first = i == 0
  177. is_last = i + 1 == len(all_words)
  178. res = highlight_word(word, before, after, is_first, is_last)
  179. processed_words.append(res)
  180. prev_prev = prev
  181. prev = sword
  182. processed.append(u" ".join(processed_words))
  183. i += 1
  184. return u"<br /><br />".join(processed)
  185. def highlight_word(word, before, after, is_first, is_last):
  186. if before and after:
  187. # Word is in the middle of a highlighted block, so don't change
  188. # anything unless this is the first word (force block to start) or
  189. # the last word (force block to end):
  190. res = word
  191. if is_first:
  192. res = u'<span class="cv-hl">' + res
  193. if is_last:
  194. res += u'</span>'
  195. elif before:
  196. # Word is the last in a highlighted block, so fade it out and then
  197. # end the block; force open a block before the word if this is the
  198. # first word:
  199. res = fade_word(word, u"out") + u"</span>"
  200. if is_first:
  201. res = u'<span class="cv-hl">' + res
  202. elif after:
  203. # Word is the first in a highlighted block, so start the block and
  204. # then fade it in; force close the block after the word if this is
  205. # the last word:
  206. res = u'<span class="cv-hl">' + fade_word(word, u"in")
  207. if is_last:
  208. res += u"</span>"
  209. else:
  210. # Word is completely outside of a highlighted block, so do nothing:
  211. res = word
  212. return res
  213. def fade_word(word, dir):
  214. if len(word) <= 4:
  215. return u'<span class="cv-hl-{0}">{1}</span>'.format(dir, word)
  216. if dir == u"out":
  217. return u'{0}<span class="cv-hl-out">{1}</span>'.format(word[:-4], word[-4:])
  218. return u'<span class="cv-hl-in">{0}</span>{1}'.format(word[:4], word[4:])
  219. def strip_word(word):
  220. return sub("[^\w\s-]", "", word.lower(), flags=UNICODE)
  221. def urlstrip(url):
  222. if url.startswith("http://"):
  223. url = url[7:]
  224. if url.startswith("https://"):
  225. url = url[8:]
  226. if url.startswith("www."):
  227. url = url[4:]
  228. if url.endswith("/"):
  229. url = url[:-1]
  230. return url
  231. %>\
  232. <%
  233. bot = bot.Bot(".earwigbot")
  234. query = parse_qs(environ["QUERY_STRING"])
  235. try:
  236. lang = query["lang"][0]
  237. project = query["project"][0]
  238. title = query["title"][0]
  239. url = query.get("url", [None])[0]
  240. except (KeyError, IndexError):
  241. page = None
  242. else:
  243. page, result = get_results(bot, lang, project, title, url, query)
  244. %>\
  245. <%include file="/support/header.mako" args="environ=environ, title='Copyvio Detector', add_css=('copyvios.css',), add_js=('copyvios.js',)"/>
  246. <h1>Copyvio Detector</h1>
  247. <p>This tool attempts to detect <a href="//en.wikipedia.org/wiki/WP:COPYVIO">copyright violations</a> in articles. Simply give the title of the page you want to check and hit Submit. The tool will then search for its content elsewhere on the web and display a report if a similar webpage is found. If you also provide a URL, it will not query any search engines and instead display a report comparing the article to that particular webpage, like the <a href="//toolserver.org/~dcoetzee/duplicationdetector/">Duplication Detector</a>. Check out the <a href="//en.wikipedia.org/wiki/User:EarwigBot/Copyvios/FAQ">FAQ</a> for more information and technical details.</p>
  248. <form action="${environ['PATH_INFO']}" method="get">
  249. <table>
  250. <tr>
  251. <td>Site:</td>
  252. <td>
  253. ${get_sites(bot)}
  254. </td>
  255. </tr>
  256. <tr>
  257. <td>Page title:</td>
  258. % if page:
  259. <td><input type="text" name="title" size="60" value="${page.title() | h}" /></td>
  260. % else:
  261. <td><input type="text" name="title" size="60" /></td>
  262. % endif
  263. </tr>
  264. <tr>
  265. <td>URL (optional):</td>
  266. % if url:
  267. <td><input type="text" name="url" size="120" value="${url | h}" /></td>
  268. % else:
  269. <td><input type="text" name="url" size="120" /></td>
  270. % endif
  271. </tr>
  272. % if query.get("nocache") or page:
  273. <tr>
  274. <td>Bypass cache:</td>
  275. % if query.get("nocache"):
  276. <td><input type="checkbox" name="nocache" value="1" checked="checked" /></td>
  277. % else:
  278. <td><input type="checkbox" name="nocache" value="1" /></td>
  279. % endif
  280. </tr>
  281. % endif
  282. <tr>
  283. <td><button type="submit">Submit</button></td>
  284. </tr>
  285. </table>
  286. </form>
  287. % if page:
  288. <div class="divider"></div>
  289. <div id="cv-result-${'yes' if result.violation else 'no'}">
  290. % if result.violation:
  291. <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>
  292. % else:
  293. <h2 id="cv-result-header">No violations detected in <a href="${page.url()}">${page.title() | h}</a>.</h2>
  294. % endif
  295. <ul id="cv-result-list">
  296. <li><b><tt>${round(result.confidence * 100, 1)}%</tt></b> confidence of a violation.</li>
  297. % if result.cached:
  298. <li>Results are <a id="cv-cached" href="#">cached
  299. <span>To save time (and money), this tool will retain the results of checks for up to 72 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. If the page is modified, a new check will be run.</span>
  300. </a> from ${result.cache_time} (${result.cache_age} ago). <a href="${environ['REQUEST_URI'] | h}&amp;nocache=1">Bypass the cache.</a></li>
  301. % else:
  302. <li>Results generated in <tt>${round(result.tdiff, 3)}</tt> seconds using <tt>${result.queries}</tt> queries.</li>
  303. % endif
  304. <li><a id="cv-result-detail-link" href="#cv-result-detail" onclick="copyvio_toggle_details()">Show details:</a></li>
  305. </ul>
  306. <div id="cv-result-detail" style="display: none;">
  307. <ul id="cv-result-detail-list">
  308. <li>Trigrams: <i>Article:</i> <tt>${result.article_chain.size()}</tt> / <i>Source:</i> <tt>${result.source_chain.size()}</tt> / <i>Delta:</i> <tt>${result.delta_chain.size()}</tt></li>
  309. % if result.cached:
  310. % if result.queries:
  311. <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>
  312. % else:
  313. <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>
  314. % endif
  315. % endif
  316. % if result.queries:
  317. <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>
  318. % endif
  319. </ul>
  320. <table id="cv-chain-table">
  321. <tr>
  322. <td>Article: <div class="cv-chain-detail"><p>${highlight_delta(result.article_chain, result.delta_chain)}</p></div></td>
  323. <td>Source: <div class="cv-chain-detail"><p>${highlight_delta(result.source_chain, result.delta_chain)}</p></div></td>
  324. </tr>
  325. </table>
  326. </div>
  327. </div>
  328. % endif
  329. <%include file="/support/footer.mako" args="environ=environ"/>