from konlpy.tag import Kkma
import os
import sys
import urllib.request
import json
import re

def naver_blog_search(client_id, client_secret, text):
    encText = urllib.parse.quote(text)
    url = "https://openapi.naver.com/v1/search/blog?query=" + encText # json 결과
    # url = "https://openapi.naver.com/v1/search/blog.xml?query=" + encText # xml 결과
    request = urllib.request.Request(url)
    request.add_header("X-Naver-Client-Id",client_id)
    request.add_header("X-Naver-Client-Secret",client_secret)
    response = urllib.request.urlopen(request)
    rescode = response.getcode()
    if(rescode==200):
        response_body = response.read()
        return response_body.decode('utf-8')
    else:
        print("Error Code:" + rescode)
    
def striphtml(data):
    p = re.compile('<.*?>')
    return p.sub('', data)

def nlp_process(word):
    result = []
    naver_result = naver_blog_search('OJgN42xxZiJXpnZtCH1j', 'crXggqJhhW', word)
    y = json.loads(naver_result)
    for b in y['items']:
        for word, pos in kkma.pos(striphtml(b['description'])):
            if pos == 'NNG' or pos == 'NNP':
                result.append(word)
                
    words = set(result)
    loofWords = list(words)
    countList = []
    for b in loofWords:
        if result.count(b) > 1:
            dic = dict()
            dic["text"] = b
            dic["size"] = result.count(b)
            countList.append(dic)
    return countList



from flask import Flask, jsonify, render_template
import requests
from bs4 import BeautifulSoup

app = Flask(__name__)
# app.config['JSON_AS_ASCII'] = False
countList = ""
kkma = Kkma()

@app.route("/<word>")
def view(word):
    countResultList = nlp_process(word)
    print(countResultList)
    countList = countResultList;
    return render_template("naver-blog-nlp-ranking-d3.html", values=countList)

if __name__ == "__main__":
    app.run(host="127.0.0.1", port="8080")