this is based on calsyslab project
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.

340 lines
13 KiB

1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
1 year ago
  1. __author__ = 'DarkWeb'
  2. import codecs
  3. import glob
  4. import os
  5. import shutil
  6. from Forums.DB_Connection.db_connection import *
  7. from Forums.BestCardingWorld.parser import *
  8. from Forums.CryptBB.parser import *
  9. import re
  10. from Forums.Classifier.classify_product import predict
  11. # from DarkWebMining_Sample.Forums.Classifier.classify_product import predict_semi
  12. # determines if forum is russian, not really used now but maybe later
  13. def isRussianForum(forum):
  14. with open('russian_forums.txt') as f:
  15. forums = f.readlines()
  16. result = False
  17. for iforum in forums:
  18. iforum = iforum.replace('\n','')
  19. if iforum == forum:
  20. result = True
  21. break
  22. return result
  23. #tries to match description pages to listing pages by using a key made for every description page and every link in listing page
  24. #once verified and matched, the info is merged into a 'rec', which is returned
  25. #@param: detPage is a list of keys of valid pages, rec is the row of data of an instance
  26. #return: rec, row of data, that may have additional data added on after matching description to listing page
  27. def mergePages(rmm, rec):
  28. # key = u"Top:" + rec[1].upper().strip() + u" User:" + rec[5].upper().strip()
  29. # key = rec[16]
  30. print ("----------------- Matched: " + rec[3] + "--------------------")
  31. rec[9] = rmm[1]
  32. rec[10] = rmm[2]
  33. rec[11] = rmm[3]
  34. rec[12] = rmm[4]
  35. rec[13] = rmm[5]
  36. rec[14] = rmm[6]
  37. rec[15] = rmm[7]
  38. rec[16] = rmm[8]
  39. return rec
  40. #gets a string of posts and joins them together into one string to be put in the database as one string of text
  41. #@param: list of strings (the posts of a thread)
  42. #return: string containing the concatenation of all the strings
  43. def getPosts(posts):
  44. strPosts = ' '.join(posts)
  45. return strPosts.strip()
  46. #uses db connection , another program, methods to persists values to the correct categories
  47. #@param: row is the list of entries for this instance, cur is the db connection object
  48. def persist_data(url, row, cur):
  49. forum = create_forum(cur, row, url)
  50. board = create_board(cur, row, forum)
  51. author = create_user(cur, row, forum, 0)
  52. topic = create_topic(cur, row, forum, board, author)
  53. create_posts(cur, row, forum, board, topic)
  54. #main method for this program, what actually gets the parsed info from the parser, and persists them into the db
  55. #calls the different parser methods here depending on the type of html page
  56. def new_parse(forum, url, createLog):
  57. from Forums.Initialization.forums_mining import CURRENT_DATE
  58. print("Parsing The " + forum + " Forum and conduct data classification to store the information in the database.")
  59. # ini = time.time()
  60. # Connecting to the database
  61. con = connectDataBase()
  62. cur = con.cursor()
  63. # Creating the tables (The database should be created manually)
  64. create_database(cur, con)
  65. nError = 0
  66. lines = [] # listing pages
  67. lns = [] # description pages
  68. detPage = {} # first pages
  69. other = {} # other pages
  70. # Creating the log file for each Forum
  71. if createLog:
  72. if not os.path.exists("./" + forum + "/Logs/" + forum + "_" + CURRENT_DATE + ".log"):
  73. logFile = open("./" + forum + "/Logs/" + forum + "_" + CURRENT_DATE + ".log", "w")
  74. else:
  75. print("Files of the date " + CURRENT_DATE + " from the Forum " + forum +
  76. " were already read. Delete the referent information in the Data Base and also delete the log file"
  77. " in the _Logs folder to read files from this Forum of this date again.")
  78. raise SystemExit
  79. # Reading the Listing Html Pages -> to memory
  80. for fileListing in glob.glob(os.path.join("..\\" + forum + "\\HTML_Pages\\" + CURRENT_DATE + "\\Listing", '*.html')):
  81. lines.append(fileListing)
  82. # Reading the Description Html Pages -> to memory
  83. for fileDescription in glob.glob(os.path.join("..\\" + forum + "\\HTML_Pages\\" + CURRENT_DATE + "\\Description" ,'*.html')):
  84. lns.append(fileDescription)
  85. # Parsing the Description Pages and put the tag's content into a dictionary (Hash table)
  86. for index, line2 in enumerate(lns):
  87. print("Reading description folder of '" + forum + "', file '" + os.path.basename(line2) + "', index= " + str(index + 1) + " ... " + str(len(lns)))
  88. try:
  89. html = codecs.open(line2.strip('\n'), encoding='utf8')#trying t open them in utf8 format
  90. soup = BeautifulSoup(html, "html.parser")#throw into beautiful soup
  91. html.close()
  92. except:
  93. try:
  94. html = open(line2.strip('\n'))
  95. soup = BeautifulSoup(html, "html.parser")
  96. html.close()
  97. except:
  98. nError += 1
  99. print("There was a problem to read the file " + line2 + " in the Description section!")
  100. if createLog:
  101. logFile.write(str(nError) + ". There was a problem to read the file " + line2 + " in the Description section!\n")
  102. continue
  103. try:
  104. #Where actual parsing occurs
  105. if forum == "BestCardingWorld":
  106. rmm = bestcardingworld_description_parser(soup)
  107. elif forum == "CryptBB":
  108. rmm = cryptBB_description_parser(soup)
  109. # key = u"Top:" + rmm[0].upper().strip() + u" User:" + rmm[2][0].upper().strip()
  110. #essentially filename and url
  111. key = u"Url:" + os.path.basename(line2).replace(".html", "")#should end with either no(page+num) or no page+num
  112. # check if page or page exists at the end of a string followed by a series of numbers
  113. #if yes add to other if no add to first page dictionary
  114. # save descritions into record in memory
  115. check = re.compile(r'(?<=Page|page)[0-9]*')
  116. if check.search(key):
  117. # print(key, 'is an other page\n')
  118. other[key] = {'rmm': rmm, 'filename': os.path.basename(line2)}
  119. else:
  120. # print(key, 'is a first page\n')
  121. detPage[key] = {'rmm': rmm, 'files': [os.path.basename(line2)]}
  122. except:
  123. nError += 1
  124. print("There was a problem to parse the file " + line2 + " in the Description section!")
  125. if createLog:
  126. logFile.write(str(nError) + ". There was a problem to parse the file " + line2 + " in the Description section.\n")
  127. # goes through keys from detPage and other, checks if the keys match.
  128. # if yes adds other[key] values to detPage w/o overwritting
  129. for key in detPage.keys():
  130. for k in list(other.keys()):
  131. checkkey = str(key[4:])
  132. checkk = str(k[4:])
  133. if checkkey in checkk:
  134. detPage[key]['rmm'][1].extend(other[k]['rmm'][1])
  135. detPage[key]['rmm'][2].extend(other[k]['rmm'][2])
  136. detPage[key]['rmm'][3].extend(other[k]['rmm'][3])
  137. detPage[key]['rmm'][4].extend(other[k]['rmm'][4])
  138. detPage[key]['rmm'][5].extend(other[k]['rmm'][5])
  139. detPage[key]['rmm'][6].extend(other[k]['rmm'][6])
  140. detPage[key]['rmm'][7].extend(other[k]['rmm'][7])
  141. detPage[key]['rmm'][8].extend(other[k]['rmm'][8])
  142. detPage[key]['files'].append(other[k]['filename'])
  143. other.pop(k)
  144. # Parsing the Listing Pages and put the tag's content into a list
  145. for index, line1 in enumerate(lines):
  146. print("Reading listing folder of '" + forum + "', file '" + os.path.basename(line1) + "', index= " + str(index + 1) + " ... " + str(len(lines)))
  147. readError = False
  148. try:
  149. html = codecs.open(line1.strip('\n'), encoding='utf8')
  150. soup = BeautifulSoup(html, "html.parser")
  151. html.close()
  152. except:
  153. try:
  154. html = open(line1.strip('\n'))
  155. soup = BeautifulSoup(html, "html.parser")
  156. html.close()
  157. except:
  158. nError += 1
  159. print("There was a problem to read the file " + line1 + " in the Listing section!")
  160. if createLog:
  161. logFile.write(str(nError) + ". There was a problem to read the file " + line1 + " in the Listing section.\n")
  162. readError = True
  163. if not readError:
  164. parseError = False
  165. try:
  166. if forum == "BestCardingWorld":
  167. rw = bestcardingworld_listing_parser(soup)
  168. elif forum == "CryptBB":
  169. rw = cryptBB_listing_parser(soup)
  170. except:
  171. nError += 1
  172. print("There was a problem to read the file " + line1 + " in the listing section!")
  173. traceback.print_exc()
  174. if createLog:
  175. logFile.write(
  176. str(nError) + ". There was a problem to read the file " + line1 + " in the Listing section.\n")
  177. parseError = True
  178. if not parseError:
  179. persistError = False
  180. moveError = False
  181. num_in_db = 0
  182. num_persisted_moved = 0
  183. for rec in rw:
  184. rec = rec.split(',')
  185. # key = u"Top:" + rec[1].upper().strip() + u" User:" + rec[5].upper().strip()
  186. key = u"Url:" + cleanLink(rec[6])
  187. if key in detPage:
  188. # Combining the information from Listing and Description Pages
  189. rmm = detPage[key]['rmm']
  190. rec = mergePages(rmm, rec)
  191. # Append to the list the classification of the topic
  192. # if isRussianForum(forum):
  193. # rec.append(str(predict(rec[1], getPosts(rec[8]), language='sup_russian')))
  194. # else:
  195. # rec.append(str(predict(rec[1], getPosts(rec[8]), language='sup_english')))
  196. rec.append(str(predict(rec[3], getPosts(rec[14]), language='sup_english')))
  197. # Persisting the information in the database
  198. try:
  199. persist_data(url, tuple(rec), cur)
  200. con.commit()
  201. except:
  202. trace = traceback.format_exc()
  203. if trace.find("already exists") == -1:
  204. nError += 1
  205. print("There was a problem to persist the file " + detPage[key]['filename'] + " in the database!")
  206. if createLog:
  207. logFile.write(
  208. str(nError) + ". There was a problem to persist the file " + detPage[key]['filename'] + " in the database.\n")
  209. persistError = True
  210. con.rollback()
  211. if not persistError:
  212. # move description files of completed folder
  213. for filename in detPage[key]['files']:
  214. source = line2.replace(os.path.basename(line2), "") + filename
  215. destination = line2.replace(os.path.basename(line2), "") + r'Read/'
  216. try:
  217. shutil.move(source, destination)
  218. num_persisted_moved += 1
  219. except:
  220. print("There was a problem to move the file " + filename + " in the Description section!")
  221. nError += 1
  222. if createLog:
  223. logFile.write(
  224. str(nError) + ". There was a problem to move the file " + filename + " in the Description section!.\n")
  225. moveError = True
  226. # if the associated description page is not read or not parsed
  227. else:
  228. # query database
  229. # if the post already exists:
  230. # num_in_db += 1
  231. pass
  232. # if number of topics on listing page is equal to
  233. # the number of merged, persisted, and moved topics plus
  234. # the number of topics already in the database
  235. if not persistError and not moveError and len(rw) == (num_persisted_moved + num_in_db):
  236. # move listing file to completed folder
  237. source = line1
  238. destination = line1.replace(os.path.basename(line1), "") + r'Read/'
  239. try:
  240. shutil.move(source, destination)
  241. except:
  242. nError += 1
  243. print("There was a problem to move the file " + line1 + " in the Listing section!")
  244. if createLog:
  245. logFile.write(str(nError) + ". There was a problem to move the file " + line1 + " in the Listing section!.\n")
  246. if createLog:
  247. logFile.close()
  248. #end = time.time()
  249. #finalTime = float(end-ini)
  250. #print (forum + " Parsing Perfomed Succesfully in %.2f" %finalTime + "!")
  251. input("Parsing the " + forum + " forum and data classification done successfully. Press ENTER to continue\n")