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 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 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, 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.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"/>