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.

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