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.

347 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. __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.OnniForums.parser import *
  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 config, 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. mainDir = os.path.join(config.get('Project', 'shared_folder'), "Forums/" + forum + "/HTML_Pages")
  80. # Reading the Listing Html Pages
  81. for fileListing in glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Listing", '*.html')):
  82. lines.append(fileListing)
  83. # Reading the Description Html Pages
  84. for fileDescription in glob.glob(os.path.join(mainDir, CURRENT_DATE + "\\Description", '*.html')):
  85. lns.append(fileDescription)
  86. # Parsing the Description Pages and put the tag's content into a dictionary (Hash table)
  87. for index, line2 in enumerate(lns):
  88. print("Reading description folder of '" + forum + "', file '" + os.path.basename(line2) + "', index= " + str(index + 1) + " ... " + str(len(lns)))
  89. try:
  90. html = codecs.open(line2.strip('\n'), encoding='utf8')
  91. soup = BeautifulSoup(html, "html.parser")
  92. html.close()
  93. except:
  94. try:
  95. html = open(line2.strip('\n'))
  96. soup = BeautifulSoup(html, "html.parser")
  97. html.close()
  98. except:
  99. nError += 1
  100. print("There was a problem to read the file " + line2 + " in the Description section!")
  101. if createLog:
  102. logFile.write(str(nError) + ". There was a problem to read the file " + line2 + " in the Description section!\n")
  103. continue
  104. try:
  105. if forum == "BestCardingWorld":
  106. rmm = bestcardingworld_description_parser(soup)
  107. elif forum == "CryptBB":
  108. rmm = cryptBB_description_parser(soup)
  109. elif forum == "OnniForums":
  110. rmm = onniForums_description_parser(soup)
  111. # key = u"Top:" + rmm[0].upper().strip() + u" User:" + rmm[2][0].upper().strip()
  112. key = u"Url:" + os.path.basename(line2).replace(".html", "")
  113. # check if page or page exists at the end of a string followed by a series of numbers
  114. #if yes add to other if no add to first page dictionary
  115. # save descritions into record in memory
  116. check = re.compile(r'(?<=Page|page)[0-9]*')
  117. if check.search(key):
  118. # print(key, 'is an other page\n')
  119. other[key] = {'rmm': rmm, 'filename': os.path.basename(line2)}
  120. else:
  121. # print(key, 'is a first page\n')
  122. detPage[key] = {'rmm': rmm, 'files': [os.path.basename(line2)]}
  123. except:
  124. nError += 1
  125. print("There was a problem to parse the file " + line2 + " in the Description section!")
  126. if createLog:
  127. logFile.write(str(nError) + ". There was a problem to parse the file " + line2 + " in the Description section.\n")
  128. # goes through keys from detPage and other, checks if the keys match.
  129. # if yes adds other[key] values to detPage w/o overwritting
  130. for key in detPage.keys():
  131. for k in list(other.keys()):
  132. checkkey = str(key[4:])
  133. checkk = str(k[4:])
  134. if checkkey in checkk:
  135. detPage[key]['rmm'][1].extend(other[k]['rmm'][1])
  136. detPage[key]['rmm'][2].extend(other[k]['rmm'][2])
  137. detPage[key]['rmm'][3].extend(other[k]['rmm'][3])
  138. detPage[key]['rmm'][4].extend(other[k]['rmm'][4])
  139. detPage[key]['rmm'][5].extend(other[k]['rmm'][5])
  140. detPage[key]['rmm'][6].extend(other[k]['rmm'][6])
  141. detPage[key]['rmm'][7].extend(other[k]['rmm'][7])
  142. detPage[key]['rmm'][8].extend(other[k]['rmm'][8])
  143. detPage[key]['files'].append(other[k]['filename'])
  144. other.pop(k)
  145. # Parsing the Listing Pages and put the tag's content into a list
  146. for index, line1 in enumerate(lines):
  147. print("Reading listing folder of '" + forum + "', file '" + os.path.basename(line1) + "', index= " + str(index + 1) + " ... " + str(len(lines)))
  148. readError = False
  149. try:
  150. html = codecs.open(line1.strip('\n'), encoding='utf8')
  151. soup = BeautifulSoup(html, "html.parser")
  152. html.close()
  153. except:
  154. try:
  155. html = open(line1.strip('\n'))
  156. soup = BeautifulSoup(html, "html.parser")
  157. html.close()
  158. except:
  159. nError += 1
  160. print("There was a problem to read the file " + line1 + " in the Listing section!")
  161. if createLog:
  162. logFile.write(str(nError) + ". There was a problem to read the file " + line1 + " in the Listing section.\n")
  163. readError = True
  164. if not readError:
  165. parseError = False
  166. try:
  167. if forum == "BestCardingWorld":
  168. rw = bestcardingworld_listing_parser(soup)
  169. elif forum == "CryptBB":
  170. rw = cryptBB_listing_parser(soup)
  171. elif forum == "OnniForums":
  172. rw = onniForums_listing_parser(soup)
  173. except:
  174. nError += 1
  175. print("There was a problem to read the file " + line1 + " in the listing section!")
  176. traceback.print_exc()
  177. if createLog:
  178. logFile.write(
  179. str(nError) + ". There was a problem to read the file " + line1 + " in the Listing section.\n")
  180. parseError = True
  181. if not parseError:
  182. persistError = False
  183. moveError = False
  184. num_in_db = 0
  185. num_persisted_moved = 0
  186. for rec in rw:
  187. rec = rec.split(',')
  188. # print(rec)
  189. # key = u"Top:" + rec[1].upper().strip() + u" User:" + rec[5].upper().strip()
  190. key = u"Url:" + cleanLink(rec[6])
  191. print(key)
  192. if key in detPage:
  193. # Combining the information from Listing and Description Pages
  194. rmm = detPage[key]['rmm']
  195. rec = mergePages(rmm, rec)
  196. # Append to the list the classification of the topic
  197. # if isRussianForum(forum):
  198. # rec.append(str(predict(rec[1], getPosts(rec[8]), language='sup_russian')))
  199. # else:
  200. # rec.append(str(predict(rec[1], getPosts(rec[8]), language='sup_english')))
  201. rec.append(str(predict(rec[3], getPosts(rec[14]), language='sup_english')))
  202. # Persisting the information in the database
  203. try:
  204. persist_data(url, tuple(rec), cur)
  205. con.commit()
  206. except:
  207. trace = traceback.format_exc()
  208. if trace.find("already exists") == -1:
  209. nError += 1
  210. print("There was a problem to persist the file " + detPage[key]['filename'] + " in the database!")
  211. if createLog:
  212. logFile.write(
  213. str(nError) + ". There was a problem to persist the file " + detPage[key]['filename'] + " in the database.\n")
  214. persistError = True
  215. con.rollback()
  216. if not persistError:
  217. # move description files of completed folder
  218. for filename in detPage[key]['files']:
  219. source = line2.replace(os.path.basename(line2), "") + filename
  220. destination = line2.replace(os.path.basename(line2), "") + r'Read/'
  221. try:
  222. shutil.move(source, destination)
  223. num_persisted_moved += 1
  224. except:
  225. print("There was a problem to move the file " + filename + " in the Description section!")
  226. nError += 1
  227. if createLog:
  228. logFile.write(
  229. str(nError) + ". There was a problem to move the file " + filename + " in the Description section!.\n")
  230. moveError = True
  231. # if the associated description page is not read or not parsed
  232. else:
  233. # query database
  234. # if the post already exists:
  235. # num_in_db += 1
  236. pass
  237. # if number of topics on listing page is equal to
  238. # the number of merged, persisted, and moved topics plus
  239. # the number of topics already in the database
  240. if not persistError and not moveError and len(rw) == (num_persisted_moved + num_in_db):
  241. # move listing file to completed folder
  242. source = line1
  243. destination = line1.replace(os.path.basename(line1), "") + r'Read/'
  244. try:
  245. shutil.move(source, destination)
  246. except:
  247. nError += 1
  248. print("There was a problem to move the file " + line1 + " in the Listing section!")
  249. if createLog:
  250. logFile.write(str(nError) + ". There was a problem to move the file " + line1 + " in the Listing section!.\n")
  251. if createLog:
  252. logFile.close()
  253. #end = time.time()
  254. #finalTime = float(end-ini)
  255. #print (forum + " Parsing Perfomed Succesfully in %.2f" %finalTime + "!")
  256. input("Parsing the " + forum + " forum and data classification done successfully. Press ENTER to continue\n")