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.

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