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.
 
 
 
 
 

412 lines
20 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 exceptions
  11. from earwigbot.bot import Bot
  12. import oursql
  13. def get_results(bot, lang, project, all_projects, title, url, query):
  14. site = get_site(bot, lang, project, 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, 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=lang)
  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. projects.add(("wikimedia", "Wikimedia"))
  140. for special in site:
  141. if "closed" not in special and "private" not in special:
  142. code = special["dbname"]
  143. name = special["code"].capitalize()
  144. languages.add((code, name))
  145. continue
  146. this = set()
  147. for web in site["site"]:
  148. if "closed" in web:
  149. continue
  150. project = "wikipedia" if web["code"] == u"wiki" else web["code"]
  151. this.add((project, project.capitalize()))
  152. if this:
  153. code = site["code"]
  154. name = site["name"].encode("unicode_escape")
  155. languages.add((code, u"{0} ({1})".format(code, name)))
  156. projects |= this
  157. save_site_updates(cursor, languages, projects)
  158. def save_site_updates(cursor, languages, projects):
  159. query1 = "SELECT lang_code, lang_name FROM language"
  160. query2 = "DELETE FROM language WHERE lang_code = ? AND lang_name = ?"
  161. query3 = "INSERT INTO language VALUES (?, ?)"
  162. query4 = "SELECT project_code, project_name FROM project"
  163. query5 = "DELETE FROM project WHERE project_code = ? AND project_name = ?"
  164. query6 = "INSERT INTO project VALUES (?, ?)"
  165. query7 = "SELECT 1 FROM updates WHERE update_service = ?"
  166. query8 = "UPDATE updates SET update_time = ? WHERE update_service = ?"
  167. query9 = "INSERT INTO updates VALUES (?, ?)"
  168. synchronize_sites_with_db(cursor, languages, query1, query2, query3)
  169. synchronize_sites_with_db(cursor, projects, query4, query5, query6)
  170. cursor.execute(query7, ("sites",))
  171. if cursor.fetchall():
  172. cursor.execute(query8, (time(), "sites"))
  173. else:
  174. cursor.execute(query9, ("sites", time()))
  175. def synchronize_sites_with_db(cursor, updates, q_list, q_rmv, q_update):
  176. removals = []
  177. cursor.execute(q_list)
  178. for site in cursor:
  179. updates.remove(site) if site in updates else removals.append(site)
  180. cursor.executemany(q_rmv, removals)
  181. cursor.executemany(q_update, updates)
  182. def highlight_delta(chain, delta):
  183. processed = []
  184. prev_prev = prev = chain.START
  185. i = 0
  186. all_words = chain.text.split()
  187. paragraphs = chain.text.split("\n")
  188. for paragraph in paragraphs:
  189. processed_words = []
  190. words = paragraph.split(" ")
  191. for word, i in zip(words, count(i)):
  192. try:
  193. next = strip_word(all_words[i+1])
  194. except IndexError:
  195. next = chain.END
  196. sword = strip_word(word)
  197. block = [prev_prev, prev] # Block for before
  198. alock = [prev, sword] # Block for after
  199. before = [block in delta.chain and sword in delta.chain[block]]
  200. after = [alock in delta.chain and next in delta.chain[alock]]
  201. is_first = i == 0
  202. is_last = i + 1 == len(all_words)
  203. res = highlight_word(word, before, after, is_first, is_last)
  204. processed_words.append(res)
  205. prev_prev = prev
  206. prev = sword
  207. processed.append(u" ".join(processed_words))
  208. i += 1
  209. return u"<br /><br />".join(processed)
  210. def highlight_word(word, before, after, is_first, is_last):
  211. if before and after:
  212. # Word is in the middle of a highlighted block, so don't change
  213. # anything unless this is the first word (force block to start) or
  214. # the last word (force block to end):
  215. res = word
  216. if is_first:
  217. res = u'<span class="cv-hl">' + res
  218. if is_last:
  219. res += u'</span>'
  220. elif before:
  221. # Word is the last in a highlighted block, so fade it out and then
  222. # end the block; force open a block before the word if this is the
  223. # first word:
  224. res = fade_word(word, u"out") + u"</span>"
  225. if is_first:
  226. res = u'<span class="cv-hl">' + res
  227. elif after:
  228. # Word is the first in a highlighted block, so start the block and
  229. # then fade it in; force close the block after the word if this is
  230. # the last word:
  231. res = u'<span class="cv-hl">' + fade_word(word, u"in")
  232. if is_last:
  233. res += u"</span>"
  234. else:
  235. # Word is completely outside of a highlighted block, so do nothing:
  236. res = word
  237. return res
  238. def fade_word(word, dir):
  239. if len(word) <= 4:
  240. return u'<span class="cv-hl-{0}">{1}</span>'.format(dir, word)
  241. if dir == u"out":
  242. return u'{0}<span class="cv-hl-out">{1}</span>'.format(word[:-4], word[-4:])
  243. return u'<span class="cv-hl-in">{0}</span>{1}'.format(word[:4], word[4:])
  244. def strip_word(word):
  245. return sub("[^\w\s-]", "", word.lower(), flags=UNICODE)
  246. def urlstrip(url):
  247. if url.startswith("http://"):
  248. url = url[7:]
  249. if url.startswith("https://"):
  250. url = url[8:]
  251. if url.startswith("www."):
  252. url = url[4:]
  253. if url.endswith("/"):
  254. url = url[:-1]
  255. return url
  256. %>\
  257. <%
  258. bot = Bot(".earwigbot")
  259. site = bot.wiki.get_site()
  260. query = parse_qs(environ["QUERY_STRING"])
  261. lang = query["lang"][0].decode("utf8").lower() if "lang" in query else None
  262. project = query["project"][0].decode("utf8").lower() if "project" in query else None
  263. title = query["title"][0].decode("utf8") if "title" in query else None
  264. url = query["url"][0].decode("utf8") if "url" in query else None
  265. all_langs, all_projects = get_sites(bot)
  266. if lang and project and title:
  267. page, result = get_results(bot, lang, project, all_projects, title,
  268. url, query)
  269. else:
  270. page = result = None
  271. %>\
  272. <%include file="/support/header.mako" args="environ=environ, title='Copyvio Detector', add_css=('copyvios.css',), add_js=('copyvios.js',)"/>
  273. <h1>Copyvio Detector</h1>
  274. <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>
  275. <form action="${environ['PATH_INFO']}" method="get">
  276. <table>
  277. <tr>
  278. <td>Site:</td>
  279. <td>
  280. http://
  281. <select name="lang">
  282. <% selected_lang = lang if lang else site.lang %>
  283. % for code, name in all_langs:
  284. % if code == selected_lang:
  285. <option value="${code}" selected="selected">${name}</option>
  286. % else:
  287. <option value="${code}">${name}</option>
  288. % endif
  289. % endfor
  290. </select>
  291. .
  292. <select name="project">
  293. <% selected_project = project if project else site.project %>
  294. % for code, name in all_projects:
  295. % if code == selected_project:
  296. <option value="${code}" selected="selected">${name}</option>
  297. % else:
  298. <option value="${code}">${name}</option>
  299. % endif
  300. % endfor
  301. </select>
  302. .org
  303. </td>
  304. </tr>
  305. <tr>
  306. <td>Page title:</td>
  307. % if page:
  308. <td><input type="text" name="title" size="60" value="${page.title | h}" /></td>
  309. % elif title:
  310. <td><input type="text" name="title" size="60" value="${title | h}" /></td>
  311. % else:
  312. <td><input type="text" name="title" size="60" /></td>
  313. % endif
  314. </tr>
  315. <tr>
  316. <td>URL (optional):</td>
  317. % if url:
  318. <td><input type="text" name="url" size="120" value="${url | h}" /></td>
  319. % else:
  320. <td><input type="text" name="url" size="120" /></td>
  321. % endif
  322. </tr>
  323. % if query.get("nocache") or page:
  324. <tr>
  325. <td>Bypass cache:</td>
  326. % if query.get("nocache"):
  327. <td><input type="checkbox" name="nocache" value="1" checked="checked" /></td>
  328. % else:
  329. <td><input type="checkbox" name="nocache" value="1" /></td>
  330. % endif
  331. </tr>
  332. % endif
  333. <tr>
  334. <td><button type="submit">Submit</button></td>
  335. </tr>
  336. </table>
  337. </form>
  338. % if project and lang and title and not page:
  339. <div class="divider"></div>
  340. <div id="cv-result-yes">
  341. <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>
  342. </div>
  343. % elif project and lang and title and page and not result:
  344. <div class="divider"></div>
  345. <div id="cv-result-yes">
  346. <p>The given page, <a href="${page.url}">${page.title | h}</a>, doesn't seem to exist.</p>
  347. </div>
  348. % elif page:
  349. <div class="divider"></div>
  350. <div id="cv-result-${'yes' if result.violation else 'no'}">
  351. % if result.violation:
  352. <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>
  353. % else:
  354. <h2 id="cv-result-header">No violations detected in <a href="${page.url()}">${page.title | h}</a>.</h2>
  355. % endif
  356. <ul id="cv-result-list">
  357. <li><b><tt>${round(result.confidence * 100, 1)}%</tt></b> confidence of a violation.</li>
  358. % if result.cached:
  359. <li>Results are <a id="cv-cached" href="#">cached
  360. <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>
  361. </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>
  362. % else:
  363. <li>Results generated in <tt>${round(result.tdiff, 3)}</tt> seconds using <tt>${result.queries}</tt> queries.</li>
  364. % endif
  365. <li><a id="cv-result-detail-link" href="#cv-result-detail" onclick="copyvio_toggle_details()">Show details:</a></li>
  366. </ul>
  367. <div id="cv-result-detail" style="display: none;">
  368. <ul id="cv-result-detail-list">
  369. <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>
  370. % if result.cached:
  371. % if result.queries:
  372. <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>
  373. % else:
  374. <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>
  375. % endif
  376. % endif
  377. % if result.queries:
  378. <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>
  379. % endif
  380. </ul>
  381. <table id="cv-chain-table">
  382. <tr>
  383. <td>Article: <div class="cv-chain-detail"><p>${highlight_delta(result.article_chain, result.delta_chain)}</p></div></td>
  384. <td>Source: <div class="cv-chain-detail"><p>${highlight_delta(result.source_chain, result.delta_chain)}</p></div></td>
  385. </tr>
  386. </table>
  387. </div>
  388. </div>
  389. % endif
  390. <%include file="/support/footer.mako" args="environ=environ"/>