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.

405 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 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 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 psycopg2.extras import RealDictCursor
  7. from Forums.DB_Connection.db_connection import *
  8. from Forums.BestCardingWorld.parser import *
  9. from Forums.CryptBB.parser import *
  10. from Forums.Incogsnoo.parser import *
  11. from Forums.Classifier.classify_product import predict
  12. # from DarkWebMining_Sample.Forums.Classifier.classify_product import predict_semi
  13. from Translator.translate import translate
  14. # controls the log id
  15. nError = 0
  16. # determines if forum is russian, not really used now but maybe later
  17. def isRussianForum(forum):
  18. with open('russian_forums.txt') as f:
  19. forums = f.readlines()
  20. result = False
  21. for iforum in forums:
  22. iforum = iforum.replace('\n','')
  23. if iforum == forum:
  24. result = True
  25. break
  26. return result
  27. #tries to match description pages to listing pages by using a key made for every description page and every link in listing page
  28. #once verified and matched, the info is merged into a 'rec', which is returned
  29. #@param: detPage is a list of keys of valid pages, rec is the row of data of an instance
  30. #return: rec, row of data, that may have additional data added on after matching description to listing page
  31. def mergePages(rmm, rec):
  32. # key = u"Top:" + rec[1].upper().strip() + u" User:" + rec[5].upper().strip()
  33. # key = rec[16]
  34. print ("----------------- Matched: " + rec[3] + "--------------------")
  35. if rmm[9] != "-1": # image_user
  36. rec[9] = rmm[9]
  37. rec[10] = rmm[1]
  38. rec[11] = rmm[2]
  39. rec[12] = rmm[3]
  40. rec[13] = rmm[4]
  41. rec[14] = rmm[5]
  42. rec[15] = rmm[6]
  43. rec[16] = rmm[7]
  44. rec[17] = rmm[8]
  45. rec[18] = rmm[10]
  46. return rec
  47. #gets a string of posts and joins them together into one string to be put in the database as one string of text
  48. #@param: list of strings (the posts of a thread)
  49. #return: string containing the concatenation of all the strings
  50. def getPosts(posts):
  51. strPosts = ' '.join(posts)
  52. return strPosts.strip()
  53. #uses db connection , another program, methods to persists values to the correct categories
  54. #@param: row is the list of entries for this instance, cur is the db connection object
  55. def persist_data(url, row, cur):
  56. forum = create_forum(cur, row, url)
  57. author = create_author(cur, row, forum)
  58. topic = create_topic(cur, forum, row, author)
  59. create_posts(cur, row, forum, topic)
  60. def incrementError():
  61. global nError
  62. nError += 1
  63. def read_file(filePath, createLog, logFile):
  64. try:
  65. html = codecs.open(filePath.strip('\n'), encoding='utf8')
  66. soup = BeautifulSoup(html, "html.parser")
  67. html.close()
  68. time.sleep(0.01) # making sure the file is closed before returning soup object
  69. return soup
  70. except:
  71. try:
  72. html = open(filePath.strip('\n'))
  73. soup = BeautifulSoup(html, "html.parser")
  74. html.close()
  75. time.sleep(0.01) # making sure the file is closed before returning soup object
  76. return soup
  77. except:
  78. incrementError()
  79. print("There was a problem to read the file " + filePath)
  80. if createLog:
  81. logFile.write(
  82. str(nError) + ". There was a problem to read the file " + filePath + "\n" + traceback.format_exc() + "\n")
  83. return None
  84. def parse_listing(forum, listingFile, soup, createLog, logFile):
  85. try:
  86. if forum == "BestCardingWorld":
  87. rw = bestcardingworld_listing_parser(soup)
  88. elif forum == "CryptBB":
  89. rw = cryptBB_listing_parser(soup)
  90. elif forum == "Incogsnoo":
  91. rw = incogsnoo_listing_parser(soup)
  92. else:
  93. print("MISSING CALL TO LISTING PARSER IN PREPARE_PARSER.PY!")
  94. raise Exception
  95. return rw
  96. except:
  97. incrementError()
  98. print("There was a problem to parse the file " + listingFile + " in the listing section!")
  99. traceback.print_exc()
  100. if createLog:
  101. logFile.write(
  102. str(nError) + ". There was a problem to parse the file " + listingFile + " in the Listing section.\n"
  103. + traceback.format_exc() + "\n")
  104. return None
  105. def parse_description(forum, descriptionFile, soup, createLog, logFile):
  106. try:
  107. if forum == "BestCardingWorld":
  108. rmm = bestcardingworld_description_parser(soup)
  109. elif forum == "CryptBB":
  110. rmm = cryptBB_description_parser(soup)
  111. elif forum == "Incogsnoo":
  112. rmm = incogsnoo_description_parser(soup)
  113. else:
  114. print("MISSING CALL TO DESCRIPTION PARSER IN PREPARE_PARSER.PY!")
  115. raise Exception
  116. return rmm
  117. except:
  118. incrementError()
  119. print("There was a problem to parse the file " + descriptionFile + " in the Description section!")
  120. traceback.print_exc()
  121. if createLog:
  122. logFile.write(
  123. str(nError) + ". There was a problem to parse the file " + descriptionFile + " in the Description section.\n"
  124. + traceback.format_exc() + "\n")
  125. return None
  126. def get_source_language(forum):
  127. if forum == "BestCardingWorld":
  128. lang = 'english'
  129. elif forum == "CryptBB":
  130. lang = 'english'
  131. elif forum == "Incogsnoo":
  132. lang = 'english'
  133. else:
  134. print("MISSING CALL TO GET LANGUAGE IN PREPARE_PARSER.PY!")
  135. lang = 'auto'
  136. return lang
  137. def persist_record(url, rec, cur, con, createLog, logFile, listingFile, descriptionFile):
  138. try:
  139. persist_data(url, tuple(rec), cur)
  140. con.commit()
  141. return True
  142. except:
  143. con.rollback()
  144. incrementError()
  145. print(f"There was a problem to persist the files ({listingFile} + {descriptionFile}) in the database!")
  146. traceback.print_exc()
  147. if createLog:
  148. logFile.write(
  149. str(nError) + f". There was a problem to persist the files ({listingFile} + {descriptionFile}) in the database!\n"
  150. + traceback.format_exc() + "\n")
  151. return False
  152. def move_file(filePath, createLog, logFile):
  153. source = filePath
  154. destination = filePath.replace(os.path.basename(filePath), "") + 'Read\\' + os.path.basename(filePath)
  155. try:
  156. shutil.move(source, destination, shutil.copy2)
  157. return True
  158. except:
  159. try:
  160. shutil.move(source, destination, shutil.copytree)
  161. return True
  162. except:
  163. incrementError()
  164. print("There was a problem to move the file " + filePath)
  165. traceback.print_exc()
  166. if createLog:
  167. logFile.write(
  168. str(nError) + ". There was a problem to move the file " + filePath + "\n" + traceback.format_exc() + "\n")
  169. return False
  170. #main method for this program, what actually gets the parsed info from the parser, and persists them into the db
  171. #calls the different parser methods here depending on the type of html page
  172. def new_parse(forum, url, createLog):
  173. from Forums.Initialization.forums_mining import config, CURRENT_DATE
  174. global nError
  175. nError = 0
  176. print("Parsing the " + forum + " forum and conduct data classification to store the information in the database.")
  177. # Connecting to the database
  178. con = connectDataBase()
  179. cur = con.cursor(cursor_factory=RealDictCursor)
  180. # Creating the tables (The database should be created manually)
  181. create_database(cur, con)
  182. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums\\" + forum + "\\HTML_Pages")
  183. # Creating the log file for each Forum
  184. if createLog:
  185. try:
  186. logFile = open(mainDir + f"/{CURRENT_DATE}/" + forum + "_" + CURRENT_DATE + ".log", "w")
  187. except:
  188. print("Could not open log file!")
  189. createLog = False
  190. logFile = None
  191. # raise SystemExit
  192. else:
  193. logFile = None
  194. source_lang = get_source_language(forum)
  195. # Reading the Listing Html Pages
  196. listings = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing", '*.html'))
  197. listings.sort(key=os.path.getmtime)
  198. for listingIndex, listingFile in enumerate(listings):
  199. print("Reading listing folder of '" + forum + "', file '" + os.path.basename(listingFile) + "', index= " + str(
  200. listingIndex + 1) + " ... " + str(len(listings)))
  201. listingSoup = read_file(listingFile, createLog, logFile)
  202. # listing flags
  203. doParseListing = listingSoup is not None
  204. doDescription = False
  205. readDescriptionError = False
  206. parseDescriptionError = False
  207. persistDescriptionError = False
  208. moveDescriptionError = False
  209. findDescriptionError = False
  210. rw = []
  211. if doParseListing:
  212. rw = parse_listing(forum, listingFile, listingSoup, createLog, logFile)
  213. doDescription = rw is not None
  214. if doDescription:
  215. nFound = 0
  216. for rec in rw:
  217. rec = rec.split(',')
  218. descriptionPattern = cleanLink(rec[6]) + "page[0-9]*.html"
  219. # Reading the associated description Html Pages
  220. descriptions = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description", descriptionPattern))
  221. descriptions.sort(key=os.path.getmtime)
  222. nFound += len(descriptions)
  223. # Aggregate of posts from multiple description (topic) pages
  224. posts = []
  225. for descriptionIndex, descriptionFile in enumerate(descriptions):
  226. print("Reading description folder of '" + forum + "', file '" + os.path.basename(
  227. descriptionFile) + "', index= " + str(descriptionIndex + 1) + " ... " + str(len(descriptions)))
  228. descriptionSoup = read_file(descriptionFile, createLog, logFile)
  229. # description flags
  230. doParseDescription = descriptionSoup is not None
  231. doPersistRecord = False
  232. doMoveDescription = False
  233. rmm = []
  234. if doParseDescription:
  235. rmm = parse_description(forum, descriptionFile, descriptionSoup, createLog, logFile)
  236. doPersistRecord = rmm is not None
  237. else:
  238. readDescriptionError = True
  239. parseDescriptionError = True
  240. if doPersistRecord:
  241. # Combining the information from Listing and Description Pages
  242. rec = mergePages(rmm, rec)
  243. # Add the page's posts to aggregate
  244. posts += rec[15]
  245. # Classify on final description page
  246. if descriptionIndex == len(descriptions) - 1:
  247. title = translate(rec[3], source_lang)
  248. content = translate(getPosts(posts), source_lang)
  249. # classification for topic based on all posts from all pages
  250. rec[19] = str(predict(title, content, language='sup_english'))
  251. # Persisting the information in the database
  252. persistSuccess = persist_record(url, rec, cur, con, createLog, logFile, listingFile, descriptionFile)
  253. doMoveDescription = persistSuccess
  254. else:
  255. parseDescriptionError = True
  256. if doMoveDescription:
  257. # move description files of completed folder
  258. moveSuccess = move_file(descriptionFile, createLog, logFile)
  259. if not moveSuccess:
  260. moveDescriptionError = True
  261. else:
  262. moveDescriptionError = True
  263. if not (nFound > 0):
  264. findDescriptionError = True
  265. incrementError()
  266. print(f"There was a problem to locate the file(s) for {listingFile} in the Description section!")
  267. if createLog:
  268. logFile.write(
  269. str(nError) + f". There was a problem to locate the file(s) for {listingFile}"
  270. f" in the Description section!\n\n")
  271. if not (readDescriptionError or parseDescriptionError or persistDescriptionError
  272. or moveDescriptionError or findDescriptionError):
  273. # move listing files of completed folder
  274. move_file(listingFile, createLog, logFile)
  275. # registering the current forum status (up/down) and the number of scraped pages in the database
  276. forumId = verifyForum(cur, forum)
  277. if (forumId > 0):
  278. readListings = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing\\read", '*.html'))
  279. readDescriptions = glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description\\read", '*.html'))
  280. create_status(cur, forumId, CURRENT_DATE, len(readListings), len(readDescriptions), '1' if len(listings) > 0 else '0')
  281. con.commit()
  282. if createLog:
  283. logFile.close()
  284. cur.close()
  285. con.close()
  286. print("Parsing the " + forum + " forum and data classification done.")