A copyright violation detector running on Wikimedia Cloud Services https://tools.wmflabs.org/copyvios/
Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.
 
 
 
 
 

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