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.
 
 
 
 
 

421 lines
21 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, urlparse
  10. from earwigbot import exceptions
  11. from earwigbot.bot import Bot
  12. import oursql
  13. def get_results(bot, lang, project, name, all_projects, title, url, query):
  14. site = get_site(bot, lang, project, name, all_projects)
  15. if not site:
  16. return None, None
  17. page = site.get_page(title)
  18. if page.exists in [page.PAGE_MISSING, page.PAGE_INVALID]:
  19. return page, None
  20. # if url:
  21. # result = get_url_specific_results(page, url)
  22. # else:
  23. # conn = open_sql_connection(bot, "copyvioCache")
  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. mc1 = __import__("earwigbot").wiki.copyvios.MarkovChain(page.get())
  29. mc2 = __import__("earwigbot").wiki.copyvios.MarkovChain(u"This is some random textual content for a page.")
  30. mci = __import__("earwigbot").wiki.copyvios.MarkovChainIntersection(mc1, mc2)
  31. result = __import__("earwigbot").wiki.copyvios.CopyvioCheckResult(
  32. True, 0.67123, "http://example.com/", 7, mc1, (mc2, mci))
  33. # END TEST BLOCK
  34. return page, result
  35. def get_site(bot, lang, project, name, all_projects):
  36. if project not in [proj[0] for proj in all_projects]:
  37. return None
  38. if project == "wikimedia": # Special sites:
  39. try:
  40. return bot.wiki.get_site(name=name)
  41. except exceptions.SiteNotFoundError:
  42. try:
  43. return bot.wiki.add_site(lang=lang, project=project)
  44. except exceptions.APIError:
  45. return None
  46. try:
  47. return bot.wiki.get_site(lang=lang, project=project)
  48. except exceptions.SiteNotFoundError:
  49. try:
  50. return bot.wiki.add_site(lang=lang, project=project)
  51. except exceptions.APIError:
  52. return None
  53. def get_url_specific_results(page, url):
  54. t_start = time()
  55. result = page.copyvio_compare(url)
  56. result.tdiff = time() - t_start
  57. return result
  58. def open_sql_connection(bot, dbname):
  59. conn_args = bot.config.wiki["_toolserverSQL"][dbname]
  60. if "read_default_file" not in conn_args and "user" not in conn_args and "passwd" not in conn_args:
  61. conn_args["read_default_file"] = expanduser("~/.my.cnf")
  62. if "autoping" not in conn_args:
  63. conn_args["autoping"] = True
  64. if "autoreconnect" not in conn_args:
  65. conn_args["autoreconnect"] = True
  66. return oursql.connect(**conn_args)
  67. def get_cached_results(page, conn):
  68. query1 = "DELETE FROM cache WHERE cache_time < DATE_SUB(CURRENT_TIMESTAMP, INTERVAL 3 DAY)"
  69. query2 = "SELECT cache_url, cache_time, cache_queries, cache_process_time FROM cache WHERE cache_id = ? AND cache_hash = ?"
  70. pageid = page.pageid()
  71. hash = sha256(page.get()).hexdigest()
  72. t_start = time()
  73. with conn.cursor() as cursor:
  74. cursor.execute(query1)
  75. cursor.execute(query2, (pageid, hash))
  76. results = cursor.fetchall()
  77. if not results:
  78. return None
  79. url, cache_time, num_queries, original_tdiff = results[0]
  80. result = page.copyvio_compare(url)
  81. result.cached = True
  82. result.queries = num_queries
  83. result.tdiff = time() - t_start
  84. result.original_tdiff = original_tdiff
  85. result.cache_time = cache_time.strftime("%b %d, %Y %H:%M:%S UTC")
  86. result.cache_age = format_date(cache_time)
  87. return result
  88. def format_date(cache_time):
  89. diff = datetime.utcnow() - cache_time
  90. if diff.seconds > 3600:
  91. return "{0} hours".format(diff.seconds / 3600)
  92. if diff.seconds > 60:
  93. return "{0} minutes".format(diff.seconds / 60)
  94. return "{0} seconds".format(diff.seconds)
  95. def get_fresh_results(page, conn):
  96. t_start = time()
  97. result = page.copyvio_check(max_queries=10)
  98. result.cached = False
  99. result.tdiff = time() - t_start
  100. cache_result(page, result, conn)
  101. return result
  102. def cache_result(page, result, conn):
  103. pageid = page.pageid()
  104. hash = sha256(page.get()).hexdigest()
  105. query1 = "SELECT 1 FROM cache WHERE cache_id = ?"
  106. query2 = "DELETE FROM cache WHERE cache_id = ?"
  107. query3 = "INSERT INTO cache VALUES (?, ?, ?, CURRENT_TIMESTAMP, ?, ?)"
  108. with conn.cursor() as cursor:
  109. cursor.execute(query1, (pageid,))
  110. if cursor.fetchall():
  111. cursor.execute(query2, (pageid,))
  112. cursor.execute(query3, (pageid, hash, result.url, result.queries,
  113. result.tdiff))
  114. def get_sites(bot):
  115. max_staleness = 60 * 60 * 24 * 7
  116. conn = open_sql_connection(bot, "globals")
  117. query1 = "SELECT update_time FROM updates WHERE update_service = ?"
  118. query2 = "SELECT lang_code, lang_name FROM language"
  119. query3 = "SELECT project_code, project_name FROM project"
  120. with conn.cursor() as cursor:
  121. cursor.execute(query1, ("sites",))
  122. try:
  123. time_since_update = int(time() - cursor.fetchall()[0][0])
  124. except IndexError:
  125. time_since_update = time()
  126. if time_since_update > max_staleness:
  127. update_sites(bot.wiki.get_site(), cursor)
  128. cursor.execute(query2)
  129. langs = [(code, name.decode("unicode_escape")) for (code, name) in cursor.fetchall()]
  130. cursor.execute(query3)
  131. projects = cursor.fetchall()
  132. return langs, projects
  133. def update_sites(site, cursor):
  134. matrix = site.api_query(action="sitematrix")["sitematrix"]
  135. del matrix["count"]
  136. languages, projects = set(), set()
  137. for site in matrix.itervalues():
  138. if isinstance(site, list): # Special sites
  139. for special in site:
  140. if "closed" not in special and "private" not in special:
  141. full = urlparse(special["url"]).netloc
  142. lang, project = full.rsplit(".", 2)[:2]
  143. code = u"{0}::{1}".format(lang, special["dbname"])
  144. name = special["code"].capitalize()
  145. languages.add((code, u"{0} ({1})".format(lang, name)))
  146. projects.add((project, project.capitalize()))
  147. continue
  148. this = set()
  149. for web in site["site"]:
  150. if "closed" in web:
  151. continue
  152. project = "wikipedia" if web["code"] == u"wiki" else web["code"]
  153. this.add((project, project.capitalize()))
  154. if this:
  155. code = site["code"]
  156. name = site["name"].encode("unicode_escape")
  157. languages.add((code, u"{0} ({1})".format(code, name)))
  158. projects |= this
  159. save_site_updates(cursor, languages, projects)
  160. def save_site_updates(cursor, languages, projects):
  161. query1 = "SELECT lang_code, lang_name FROM language"
  162. query2 = "DELETE FROM language WHERE lang_code = ? AND lang_name = ?"
  163. query3 = "INSERT INTO language VALUES (?, ?)"
  164. query4 = "SELECT project_code, project_name FROM project"
  165. query5 = "DELETE FROM project WHERE project_code = ? AND project_name = ?"
  166. query6 = "INSERT INTO project VALUES (?, ?)"
  167. query7 = "SELECT 1 FROM updates WHERE update_service = ?"
  168. query8 = "UPDATE updates SET update_time = ? WHERE update_service = ?"
  169. query9 = "INSERT INTO updates VALUES (?, ?)"
  170. synchronize_sites_with_db(cursor, languages, query1, query2, query3)
  171. synchronize_sites_with_db(cursor, projects, query4, query5, query6)
  172. cursor.execute(query7, ("sites",))
  173. if cursor.fetchall():
  174. cursor.execute(query8, (time(), "sites"))
  175. else:
  176. cursor.execute(query9, ("sites", time()))
  177. def synchronize_sites_with_db(cursor, updates, q_list, q_rmv, q_update):
  178. removals = []
  179. cursor.execute(q_list)
  180. for site in cursor:
  181. updates.remove(site) if site in updates else removals.append(site)
  182. cursor.executemany(q_rmv, removals)
  183. cursor.executemany(q_update, updates)
  184. def highlight_delta(chain, delta):
  185. processed = []
  186. prev_prev = prev = chain.START
  187. i = 0
  188. all_words = chain.text.split()
  189. paragraphs = chain.text.split("\n")
  190. for paragraph in paragraphs:
  191. processed_words = []
  192. words = paragraph.split(" ")
  193. for word, i in zip(words, count(i)):
  194. try:
  195. next = strip_word(all_words[i+1])
  196. except IndexError:
  197. next = chain.END
  198. sword = strip_word(word)
  199. block = (prev_prev, prev) # Block for before
  200. alock = (prev, sword) # Block for after
  201. before = [block in delta.chain and sword in delta.chain[block]]
  202. after = [alock in delta.chain and next in delta.chain[alock]]
  203. is_first = i == 0
  204. is_last = i + 1 == len(all_words)
  205. res = highlight_word(word, before, after, is_first, is_last)
  206. processed_words.append(res)
  207. prev_prev = prev
  208. prev = sword
  209. processed.append(u" ".join(processed_words))
  210. i += 1
  211. return u"<br /><br />".join(processed)
  212. def highlight_word(word, before, after, is_first, is_last):
  213. if before and after:
  214. # Word is in the middle of a highlighted block, so don't change
  215. # anything unless this is the first word (force block to start) or
  216. # the last word (force block to end):
  217. res = word
  218. if is_first:
  219. res = u'<span class="cv-hl">' + res
  220. if is_last:
  221. res += u'</span>'
  222. elif before:
  223. # Word is the last in a highlighted block, so fade it out and then
  224. # end the block; force open a block before the word if this is the
  225. # first word:
  226. res = fade_word(word, u"out") + u"</span>"
  227. if is_first:
  228. res = u'<span class="cv-hl">' + res
  229. elif after:
  230. # Word is the first in a highlighted block, so start the block and
  231. # then fade it in; force close the block after the word if this is
  232. # the last word:
  233. res = u'<span class="cv-hl">' + fade_word(word, u"in")
  234. if is_last:
  235. res += u"</span>"
  236. else:
  237. # Word is completely outside of a highlighted block, so do nothing:
  238. res = word
  239. return res
  240. def fade_word(word, dir):
  241. if len(word) <= 4:
  242. return u'<span class="cv-hl-{0}">{1}</span>'.format(dir, word)
  243. if dir == u"out":
  244. return u'{0}<span class="cv-hl-out">{1}</span>'.format(word[:-4], word[-4:])
  245. return u'<span class="cv-hl-in">{0}</span>{1}'.format(word[:4], word[4:])
  246. def strip_word(word):
  247. return sub("[^\w\s-]", "", word.lower(), flags=UNICODE)
  248. def urlstrip(url):
  249. if url.startswith("http://"):
  250. url = url[7:]
  251. if url.startswith("https://"):
  252. url = url[8:]
  253. if url.startswith("www."):
  254. url = url[4:]
  255. if url.endswith("/"):
  256. url = url[:-1]
  257. return url
  258. %>\
  259. <%
  260. lang = project = name = title = url = None
  261. query = parse_qs(environ["QUERY_STRING"])
  262. if "lang" in query:
  263. lang = query["lang"][0].decode("utf8").lower()
  264. if "::" in lang:
  265. lang, name = lang.split("::", 1)
  266. if "project" in query:
  267. project = query["project"][0].decode("utf8").lower()
  268. if "title" in query:
  269. title = query["title"][0].decode("utf8")
  270. if "url" in query:
  271. url = query["url"][0].decode("utf8")
  272. bot = Bot(".earwigbot")
  273. site = bot.wiki.get_site()
  274. all_langs, all_projects = get_sites(bot)
  275. if lang and project and title:
  276. page, result = get_results(bot, lang, project, name, all_projects,
  277. title, url, query)
  278. else:
  279. page = result = None
  280. %>\
  281. <%include file="/support/header.mako" args="environ=environ, title='Copyvio Detector', add_css=('copyvios.css',), add_js=('copyvios.js',)"/>
  282. <h1>Copyvio Detector</h1>
  283. <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>
  284. <form action="${environ['PATH_INFO']}" method="get">
  285. <table>
  286. <tr>
  287. <td>Site:</td>
  288. <td>
  289. http://
  290. <select name="lang">
  291. <% selected_lang = lang if lang else site.lang %>
  292. % for code, name in all_langs:
  293. % if code == selected_lang:
  294. <option value="${code}" selected="selected">${name}</option>
  295. % else:
  296. <option value="${code}">${name}</option>
  297. % endif
  298. % endfor
  299. </select>
  300. .
  301. <select name="project">
  302. <% selected_project = project if project else site.project %>
  303. % for code, name in all_projects:
  304. % if code == selected_project:
  305. <option value="${code}" selected="selected">${name}</option>
  306. % else:
  307. <option value="${code}">${name}</option>
  308. % endif
  309. % endfor
  310. </select>
  311. .org
  312. </td>
  313. </tr>
  314. <tr>
  315. <td>Page title:</td>
  316. % if page:
  317. <td><input type="text" name="title" size="60" value="${page.title | h}" /></td>
  318. % elif title:
  319. <td><input type="text" name="title" size="60" value="${title | h}" /></td>
  320. % else:
  321. <td><input type="text" name="title" size="60" /></td>
  322. % endif
  323. </tr>
  324. <tr>
  325. <td>URL (optional):</td>
  326. % if url:
  327. <td><input type="text" name="url" size="120" value="${url | h}" /></td>
  328. % else:
  329. <td><input type="text" name="url" size="120" /></td>
  330. % endif
  331. </tr>
  332. % if query.get("nocache") or page:
  333. <tr>
  334. <td>Bypass cache:</td>
  335. % if query.get("nocache"):
  336. <td><input type="checkbox" name="nocache" value="1" checked="checked" /></td>
  337. % else:
  338. <td><input type="checkbox" name="nocache" value="1" /></td>
  339. % endif
  340. </tr>
  341. % endif
  342. <tr>
  343. <td><button type="submit">Submit</button></td>
  344. </tr>
  345. </table>
  346. </form>
  347. % if project and lang and title and not page:
  348. <div class="divider"></div>
  349. <div id="cv-result-yes">
  350. <p>The given site, (project=<b><tt>${project}</tt></b>, language=<b><tt>${lang}</tt></b>) doesn't seem to exist. <a href="//${lang}.${project}.org/">Check its URL?</a></p>
  351. </div>
  352. % elif project and lang and title and page and not result:
  353. <div class="divider"></div>
  354. <div id="cv-result-yes">
  355. <p>The given page, <a href="${page.url}">${page.title | h}</a>, doesn't seem to exist.</p>
  356. </div>
  357. % elif page:
  358. <div class="divider"></div>
  359. <div id="cv-result-${'yes' if result.violation else 'no'}">
  360. % if result.violation:
  361. <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>
  362. % else:
  363. <h2 id="cv-result-header">No violations detected in <a href="${page.url()}">${page.title | h}</a>.</h2>
  364. % endif
  365. <ul id="cv-result-list">
  366. <li><b><tt>${round(result.confidence * 100, 1)}%</tt></b> confidence of a violation.</li>
  367. % if result.cached:
  368. <li>Results are <a id="cv-cached" href="#">cached
  369. <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>
  370. </a> from ${result.cache_time} (${result.cache_age} ago). <a href="${environ['REQUEST_URI'].decode("utf8") | h}&amp;nocache=1">Bypass the cache.</a></li>
  371. % else:
  372. <li>Results generated in <tt>${round(result.tdiff, 3)}</tt> seconds using <tt>${result.queries}</tt> queries.</li>
  373. % endif
  374. <li><a id="cv-result-detail-link" href="#cv-result-detail" onclick="copyvio_toggle_details()">Show details:</a></li>
  375. </ul>
  376. <div id="cv-result-detail" style="display: none;">
  377. <ul id="cv-result-detail-list">
  378. <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>
  379. % if result.cached:
  380. % if result.queries:
  381. <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>
  382. % else:
  383. <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>
  384. % endif
  385. % endif
  386. % if result.queries:
  387. <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>
  388. % endif
  389. </ul>
  390. <table id="cv-chain-table">
  391. <tr>
  392. <td>Article: <div class="cv-chain-detail"><p>${highlight_delta(result.article_chain, result.delta_chain)}</p></div></td>
  393. <td>Source: <div class="cv-chain-detail"><p>${highlight_delta(result.source_chain, result.delta_chain)}</p></div></td>
  394. </tr>
  395. </table>
  396. </div>
  397. </div>
  398. % endif
  399. <%include file="/support/footer.mako" args="environ=environ"/>