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.

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