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.
 
 
 
 
 

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