main.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338
  1. from pydoc import HTMLDoc
  2. from fastapi import FastAPI
  3. import dataset
  4. import sys
  5. import os
  6. import time
  7. from fastapi.middleware.cors import CORSMiddleware
  8. from fastapi.staticfiles import StaticFiles
  9. from pydantic import BaseModel
  10. from fastapi import FastAPI, Form, Response, File, UploadFile, Request
  11. import subprocess
  12. import suggests
  13. from typing import Optional
  14. # import networkx as nx
  15. # import pyvis
  16. # import time
  17. # from pyvis.network import Network
  18. import pickle
  19. import logging
  20. import threading
  21. import random
  22. import string
  23. from fastapi.responses import HTMLResponse,RedirectResponse, FileResponse
  24. import dataset
  25. import traceback
  26. import time
  27. from selenium import webdriver
  28. from selenium.webdriver.common.keys import Keys
  29. from selenium.webdriver.common.by import By
  30. from selenium.webdriver.chrome.service import Service
  31. import networkx as nx
  32. from pyvis.network import Network
  33. import csv
  34. import sys
  35. import codecs
  36. import difflib
  37. import pymysql
  38. pymysql.install_as_MySQLdb()
  39. from pathlib import Path
  40. from tempfile import NamedTemporaryFile
  41. from typing import Callable
  42. import shutil
  43. # import aiofiles
  44. from io import StringIO
  45. driver = None
  46. def id_generator(size=6, chars=string.ascii_uppercase + string.digits):
  47. return ''.join(random.choice(chars) for _ in range(size))
  48. app = FastAPI()
  49. origins = ["*"]
  50. app.add_middleware(
  51. CORSMiddleware,
  52. allow_origins=origins,
  53. allow_credentials=True,
  54. allow_methods=["*"],
  55. allow_headers=["*"],
  56. )
  57. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/gtrends?charset=utf8mb4')
  58. app.mount("/web", StaticFiles(directory="/Users/mac/PycharmProjects/kw_tools/web/static"), name="static")
  59. # app.mount("/web", StaticFiles(directory="/root/src/kw_tools/web/static"), name="static")
  60. def thread_function(kw):
  61. global db
  62. print(kw)
  63. G = nx.Graph()
  64. for k in kw:
  65. s = suggests.suggests.get_suggests(k, source='google')
  66. for sg in s['suggests']:
  67. G.add_edge(k,sg,weight=1)
  68. print(sg)
  69. time.sleep(1)
  70. s2 = suggests.suggests.get_suggests(k, source='google')
  71. for elmt in s2['suggests']:
  72. G.add_edge(sg,elmt,weight=1)
  73. # G.remove_nodes_from(list(nx.isolates(G)))
  74. G.remove_edges_from( list(nx.selfloop_edges(G)))
  75. # pickle.dump( G, open( "gs2.p", "wb" ) )
  76. pyG = Network(height="750px", width="100%",bgcolor="#333333",font_color="white")
  77. pyG.from_nx(G)
  78. id=id_generator()
  79. db['gen_graph'].insert({'filename':str(id),'kw':str(kw)})
  80. # pyG.save_graph('gstest')
  81. # pyG.show('static/gs/'+str(id)+'.html')
  82. pyG.save_graph('static/gs/'+str(id)+'.html')
  83. @app.get("/tree_list/",response_class=HTMLResponse)
  84. async def tree_list():
  85. # global db
  86. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/gtrends?charset=utf8mb4')
  87. html="<html><body><h2>清單</h2></br>請一分鐘後refresh </br></br>"
  88. html+="<table border='1'>"
  89. cursor=db.query('select filename,kw from gen_graph order by id desc')
  90. cnt=0
  91. for c in cursor:
  92. html+="<tr><td>"+c['kw']+"</td>"
  93. html+="<td><a href='/web/gs/"+c['filename']+".html'>"+c['filename']+"</a></td></tr>"
  94. cnt+=1
  95. if cnt > 10:
  96. break
  97. html+="</table></body></html>"
  98. return html
  99. @app.post("/proj_kw/",response_class=HTMLResponse)
  100. async def proj_kw(proj: str = Form(...),kws:Optional[str] = Form(None)):
  101. db = dataset.connect('mysql://choozmo:pAssw0rd@db.ptt.cx:3306/seo?charset=utf8mb4')
  102. table=db['serp_jobs']
  103. for kw in kws:
  104. table.insert({'proj':proj,'kw':kw})
  105. return "OK請稍後"
  106. #response_class=RedirectResponse
  107. @app.post("/gen_tree/",response_class=HTMLResponse)
  108. async def func_expand(kw: str = Form(...),kw2:Optional[str] = Form(None),kw3:Optional[str] = Form(None),kw4:Optional[str] = Form(None) ):
  109. kwlst=[]
  110. if len(kw)>1:
  111. kwlst.append(kw)
  112. if kw2 is not None:
  113. kwlst.append(kw2)
  114. if kw3 is not None:
  115. kwlst.append(kw3)
  116. if kw4 is not None:
  117. kwlst.append(kw4)
  118. x = threading.Thread(target=thread_function, args=(kwlst,))
  119. x.start()
  120. # return "ok"
  121. return RedirectResponse(url="/tree_list",status_code=302)
  122. # return HTMLResponse('<html><head><meta http-equiv="refresh" content="0; URL="/tree_list" /></head></html>')
  123. def restart_browser():
  124. global driver
  125. if driver is not None:
  126. print('closing')
  127. driver.quit()
  128. driver = None
  129. try:
  130. options = webdriver.ChromeOptions()
  131. options.add_argument("--no-sandbox")
  132. options.add_argument("--disable-dev-shm-usage")
  133. options.add_argument('--headless')
  134. #options.add_argument('--remote-debugging-port=9222')
  135. #options.add_experimental_option("debuggerAddress", "127.0.0.1:9922")
  136. options.add_argument("--incognito")
  137. try:
  138. driver = webdriver.Chrome(options=options)
  139. str1 = driver.capabilities['chrome']['chromedriverVersion'].split(' ')[0]
  140. print('這裡',str1)
  141. #driver = webdriver.Remote(command_executor='http://127.0.0.1:'+str(portnum)+'/wd/hub',options=options)
  142. except:
  143. return None
  144. except:
  145. print('開啟失敗')
  146. driver=None
  147. return None
  148. return driver
  149. @app.post("/ranking/")
  150. async def ranking(kw: str = Form(...), domain:str = Form(...),kw2:Optional[str] = Form(None),domain2:Optional[str] = Form(None),kw3:Optional[str] = Form(None),domain3:Optional[str] = Form(None),kw4:Optional[str] = Form(None),domain4:Optional[str] = Form(None),kw5:Optional[str] = Form(None),domain5:Optional[str] = Form(None)):
  151. kwlst = []
  152. kwlst.append([kw,domain])
  153. if kw2 is not None:
  154. kwlst.append([kw2,domain2])
  155. if kw3 is not None:
  156. kwlst.append([kw3,domain3])
  157. if kw4 is not None:
  158. kwlst.append([kw4,domain4])
  159. if kw5 is not None:
  160. kwlst.append([kw5,domain5])
  161. result = []
  162. for i in kwlst:
  163. driver = restart_browser()
  164. # escaped_search_term=urllib.parse.quote(term)
  165. googleurl = 'https://www.google.com/?num=100'
  166. driver.get(googleurl)
  167. time.sleep(6)
  168. send_kw_elmt = driver.find_element(By.XPATH,
  169. '/html/body/div[1]/div[3]/form/div[1]/div[1]/div[1]/div/div[2]/input')
  170. send_kw_elmt.send_keys(i[0])
  171. time.sleep(3)
  172. send_kw_elmt.send_keys(Keys.ENTER)
  173. time.sleep(6)
  174. elmts = driver.find_elements_by_xpath("//div[@class='yuRUbf']/a")
  175. cnt = 1
  176. datadict = {'搜尋詞': [], '結果標題': [], '結果網址': [], '結果名次': []}
  177. domain_name = i[1]
  178. for elmt in elmts:
  179. try:
  180. href = elmt.get_attribute('href')
  181. if domain_name in href:
  182. datadict['搜尋詞'].append(i[0])
  183. datadict['結果標題'].append(elmt.text)
  184. datadict['結果網址'].append(href)
  185. datadict['結果名次'].append(str(cnt))
  186. cnt += 1
  187. except:
  188. print('href2 exception')
  189. traceback.print_exc()
  190. result.append(datadict)
  191. print(domain_name)
  192. print(datadict)
  193. driver.quit()
  194. print('數量',len(elmts))
  195. time.sleep(90)
  196. # return "ok"
  197. # return RedirectResponse(url="/ranking_result",)
  198. html = f"<html><body>{result}</body></html>"
  199. return html
  200. @app.get("/ranking_result/")
  201. async def tree_list():
  202. html = "<table border='1'>"
  203. # html += "<tr><td>" + c['kw'] + "</td>"
  204. return html
  205. kwdict={}
  206. G = nx.Graph()
  207. def gcm0(strings):
  208. clusters = {}
  209. for string in (x.strip() for x in strings):
  210. match = difflib.get_close_matches(string, clusters.keys(), 8, 0.65)
  211. if match:
  212. clusters[match[0]].append(string)
  213. else:
  214. clusters[string] = [ string ]
  215. return clusters
  216. def proc_row(row):
  217. print('這裡',row)
  218. elmts=row.split(' ')
  219. print(elmts)
  220. for elmt in elmts:
  221. if kwdict.get(elmt) is None:
  222. kwdict[elmt]=1
  223. else:
  224. kwdict[elmt]+=1
  225. def save_upload_file_tmp(file: UploadFile) -> Path:
  226. try:
  227. suffix = Path(file.filename).suffix
  228. with NamedTemporaryFile(delete=False, suffix=suffix) as tmp:
  229. shutil.copyfileobj(file.file, tmp)
  230. tmp_path = Path(tmp.name)
  231. finally:
  232. file.file.close()
  233. return tmp_path
  234. @app.post("/kwtree")
  235. async def kwtree(file: UploadFile = File(...)):
  236. csvfile = csv.reader(codecs.iterdecode(file.file, 'utf-8'),dialect=csv.excel)
  237. kwdict = {}
  238. addict = {}
  239. head = True
  240. rowlst = []
  241. for row in csvfile:
  242. if head:
  243. head = False
  244. continue
  245. ll = len(row)
  246. proc_row(row[0])
  247. if row not in rowlst:
  248. rowlst.append(row[0])
  249. head = True
  250. clusters = gcm0(rowlst)
  251. keys = []
  252. for k, v in clusters.items():
  253. # if len(v) > 20:
  254. keys.append(k)
  255. for x in v:
  256. G.add_edge(k, x, weight=1, label='')
  257. already_dict = {}
  258. from strsimpy.qgram import QGram
  259. qgram = QGram(2)
  260. for k1 in keys:
  261. for k2 in keys:
  262. if k1 != k2:
  263. if qgram.distance(k1, k2) <= 12:
  264. if already_dict.get(k1) is None and already_dict.get(k2) is None:
  265. already_dict[k1] = 1
  266. already_dict[k2] = 1
  267. G.add_edge(k1, k2, weight=1, label='')
  268. pyG = Network(height="100%", width="100%", bgcolor="#444444", font_color="white")
  269. pyG.set_options("""
  270. const options = {
  271. "nodes" : {
  272. "font" : {
  273. "size" : "30",
  274. "color" : "#ffffff"
  275. }
  276. },
  277. "physics": {
  278. "forceAtlas2Based": {
  279. "springLength": 100
  280. },
  281. "maxVelocity": 150,
  282. "minVelocity": 0.28,
  283. "solver": "forceAtlas2Based"
  284. }
  285. }
  286. """)
  287. G.remove_edges_from(nx.selfloop_edges(G))
  288. pyG.from_nx(G)
  289. # pyG.show_buttons(filter_=['physics'])
  290. news_file = random.randint(0,100)
  291. pyG.show(f'news{news_file}.html')
  292. check_file = False
  293. # while
  294. # print(clusters)
  295. # sys.exit()
  296. return FileResponse(f'/Users/mac/PycharmProjects/kw_tools/web/news{news_file}.html',media_type='text/html')