Spaces:
Runtime error
Runtime error
File size: 9,649 Bytes
c109682 c1654fa c109682 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 |
import os
import pandas as pd
from flask import Flask, jsonify, request, render_template
import spacy
from spacy import displacy
# ๋ชจ๋ธ์ ์ ์ฉ์ํค๋ ํ์ผ
from modules.inference import Tk_instruct
# Stocks Data
from dataset_creation.nasdaq_data import get_list, get_data
# Flask Object ์์ฑ
# __name__์ ํ์ฌ ์คํ ์ค์ธ ๋ชจ๋ ์ด๋ฆ์ ์ ๋ฌํ๋ ๊ฒ์ด๋ค.
app = Flask(__name__)
# def stocks() ์ฌ์ฉ & News Data
# Pandas DataFrame : ticker, name, sector, industry, diff, open, close, date
demo_dic = get_list()
##### Home #####
@app.route('/')
def home_page():
example_embed = 'This website analyzes stock market news and provides answers to questions related to news articles.'
return render_template('index.html', embed=example_embed)# html์ ๋ถ๋ฌ์ฌ ๋,
##### Data fetch #####
@app.route('/submit', methods=['GET', 'POST'])
def submit():
input_text = request.args.get('input_text')
return jsonify(result={"output":"My output is a summary of: "+input_text})
@app.route('/model', methods=['GET', 'POST'])
def model():
print("\t\t Start model !!!")
# Javascript ์์ ๋ฐ์ ๋ฉ์์ง
text_input = request.args.get('text_input')
print(f"Fetch from Javascript /inference, text_input : {text_input}")
# modules/reference.py ์์ ๋ชจ๋ธ ์ ์ฉ
output = Tk_instruct(text_input)
text_output = {"text_output": output}
print(f"Fetch from Javascript /inference, text_output : {text_output}")
return jsonify(result=text_output)
# Show Ticker's Table
@app.route('/stocks', methods=['GET', 'POST'])
def stocks():
result = demo_dic.to_dict() # dictionary ํํ๋ก ๋ณํ
return jsonify(result=result)
################################################################################################
# {ticker1: [{๋ ์ง1: [์ ๋ชฉ1, ์ ๋ชฉ2, ...]}, {๋ ์ง2: [์ ๋ชฉ3, ์ ๋ชฉ4, ...]}, ...], ticker2: [{๋ ์ง3: [์ ๋ชฉ5, ์ ๋ชฉ6, ...]}, {๋ ์ง4: [์ ๋ชฉ7, ์ ๋ชฉ8, ...]}, ...], ... }
ticker_dic = dict.fromkeys(demo_dic.ticker, []) # ticker1: [{๋ ์ง1: [์ ๋ชฉ1, ์ ๋ชฉ2, ...]}
dir = './news'
if not os.path.exists(dir):
raise NotImplementedError("Not exists News Data")# ์ค๋ฅ ๊ฐ์ ๋ฐ์
# News Data List ๊ฐ์ ธ์ค๊ธฐ
for key in os.listdir(dir):
if key not in ticker_dic.keys():
raise NotImplementedError("Not exists Ticker")# ์ค๋ฅ ๊ฐ์ ๋ฐ์
dir2 = os.path.join(dir, key)
ticker_dic[key] = dict.fromkeys(os.listdir(dir2), []) # ๋ ์ง1: [์ ๋ชฉ1, ์ ๋ชฉ2, ...]
for date in os.listdir(dir2):
dir3 = os.path.join(dir2, date)
title_list = [title for title in os.listdir(dir3)]
# ํด๋น ๋ ์ง์ News๊ฐ ์์ ์๋ ์์
if len(title_list) != 0:
ticker_dic[key][date] = title_list # [์ ๋ชฉ1, ์ ๋ชฉ2, ...]
else:
ticker_dic[key].pop(date)
# from IPython import embed; embed()
# Show Ticker's Title
@app.route('/<ticker>', methods=['GET', 'POST'])
def ticker(ticker):
example_embed = "%s Chart" % (ticker)
return render_template('chart.html', embed=example_embed)
# Show Ticker's Data
@app.route('/chart', methods=['GET', 'POST'])
def chart():
print("Start /chart ")
# Javascript ์์ ๋ฐ์ ๋ฉ์์ง
ticker = request.args.get('ticker')
# Implement Module
chart_data = get_data(tickers=[ticker], numOfDay=60)[0]
# ๋ ์ง ํ์ ๋ฐ๊พธ๊ธฐ
chart_data.index = [k.strftime("%Y-%m-%d") for k in chart_data.index]
result = chart_data.to_dict()
return jsonify(result=result)
@app.route('/news', methods=['GET', 'POST'])
def news():
print("Start /news ")
# Javascript ์์ ๋ฐ์ ๋ฉ์์ง
ticker = request.args.get('ticker')
news_dir = os.path.join('./news', ticker)
# ํด๋น Ticker์ ๋ ์ง๋ณ ๋ด์ค ์ ๋ชฉ์ ๊ฐ์ ธ์จ๋ค.
result = {}
for key in os.listdir(news_dir):
title_list = os.listdir(os.path.join(news_dir, key))
if len(title_list) != 0:
result[key] = os.listdir(os.path.join(news_dir, key))
# ์ต๊ทผ ๋ด์ค๋ถํฐ ๋ณด์ด๊ฒ (์ ๋ ฌ)
sorted_result = {}
for key, value in sorted(result.items(), reverse=True):
sorted_result[key] = value
return jsonify(result=sorted_result)
################################################################################################
# 1. ๊ธฐ๋ณธ url
# 2. ์ฟผ๋ฆฌ ์คํธ๋ง์ด ์กด์ฌํ๋ url
# : request.args.get('๋ณ์์ด๋ฆ')์ ์ฌ์ฉํ์ฌ /user?๋ณ์=๊ฐ&๋ณ์=๊ฐ&...์์ ์ํ๋ ๋ณ์์ ๊ฐ์ ์ป์ ์ ์๋ค.
# 3. clean URL
# Show Ticker's Title and News's Title
@app.route('/info', methods=['GET', 'POST'])
def ticker_title():
print("app.py : /info Start ")
# Javascript ์์ ๋ฐ์ ๋ฉ์์ง
ticker = request.args.get('ticker')
date = request.args.get('date')
title = request.args.get('title')
andSymbolInTitle = request.args.get('andSymbolInTitle')
# Title ์์ '&'๋ก ํ์๋์ด ์๋๋ฐ ๋ฐ๋ก ๊ตฌ๋ณํด์ผ ๋๋ค.
# andSymbolInTitle ์์ ๊ฐ์ ธ์จ '&' ์์น index๋ฅผ title๊ณผ ํฉ์ณ์ค๋ค.
if andSymbolInTitle != '':
andSymbolInTitle = andSymbolInTitle.split(',')
for i in range(len(andSymbolInTitle)): # String -> int
andSymbolInTitle[i] = int(andSymbolInTitle[i])
for idx in andSymbolInTitle:
title = title[0:idx] + '&' + title[idx:len(title)]
# ํด๋น Ticker, Date, Title์ URL์ ๊ฐ์ ธ์ค๊ธฐ
url_dir = "dataset_creation/save_news_url.tsv"
if not os.path.exists(url_dir):
raise NotImplementedError("Not exists {} directory", url_dir)
else:
df = pd.read_csv(url_dir, sep='\t', index_col=0)
filt = (df['ticker'] == ticker) & (df['date'] == date) & (df['title'] == title)
url = list(df.loc[filt, 'url'].values)
if len(url) != 1:
from IPython import embed; embed()
raise NotImplementedError("There exists many URL or empty")
else:
url = url[0]
example_embed1 = ticker
example_embed2 = "Date: %s" % (date)
example_embed3 = "Title: %s" % (title)
example_embed4 = url
return render_template('news_analysis.html', embed1=example_embed1, embed2=example_embed2, embed3=example_embed3, embed4=example_embed4)
@app.route('/ner', methods=['GET', 'POST'])
def ner():
print("Start /ner")
# Javascript ์์ ๋ฐ์ ๋ฉ์์ง
ticker = request.args.get('ticker')
date = request.args.get('date')
title = request.args.get('title')
print(ticker, date, title)
# ๋ด์ค ๋ฐ์ดํฐ ์์น ์ฐพ๊ธฐ ( in directory )
dir = os.path.join('./news', ticker, date, title+'.txt')
f = open(dir, 'r')
news_data = f.read()
# NER
nlp = spacy.load("en_core_web_sm")
doc = nlp(news_data) # News Data Analysis
# ํ์์๋ ์ฉ์ด๋ค ๋ฒ๋ฆฌ๊ธฐ
print("=====================================================================")
ents = {'text': [], 'start_char': [], 'end_char': [], 'label_': []}
for ent in doc.ents:
# print(ent.text, ent.start_char, ent.end_char, ent.label_)
# ๋ฒ๋ฆฌ๋ ์ฉ์ด๋ค
if ent.label_ == 'DATE':
continue
if ent.label_ == 'TIME':
continue
if ent.label_ == 'CARDINAL':
continue
if ent.label_ == 'MONEY':
continue
if ent.label_ == 'PERCENT':
continue
if ent.label_ == 'ORDINAL':
continue
print(ent.text, ent.start_char, ent.end_char, ent.label_)
ents['text'].append(ent.text)
ents['start_char'].append(ent.start_char)
ents['end_char'].append(ent.end_char)
ents['label_'].append(ent.label_)
print("=====================================================================")
ents['news'] = news_data
# ents = {'text': [], 'start_char': [], 'end_char': [], 'label_': [], 'news': []}
return jsonify(result=ents)
@app.route('/newsQuestions', methods=['GET', 'POST'])
def newsQuestions():
# Javascript ์์ ๋ฐ์ ๋ฉ์์ง
ticker = request.args.get('ticker')
date = request.args.get('date')
title = request.args.get('title')
andSymbolInTitle = request.args.get('andSymbolInTitle')
questions = request.args.get('questions')
# Title ์์ '&'๋ก ํ์๋์ด ์๋๋ฐ ๋ฐ๋ก ๊ตฌ๋ณํด์ผ ๋๋ค.
# andSymbolInTitle ์์ ๊ฐ์ ธ์จ '&' ์์น index๋ฅผ title๊ณผ ํฉ์ณ์ค๋ค.
if andSymbolInTitle != '':
andSymbolInTitle = andSymbolInTitle.split(',')
for i in range(len(andSymbolInTitle)): # String -> int
andSymbolInTitle[i] = int(andSymbolInTitle[i])
for idx in andSymbolInTitle:
title = title[0:idx] + '&' + title[idx:len(title)]
# ๋ด์ค ๋ฐ์ดํฐ ์์น ์ฐพ๊ธฐ ( in directory )
dir = os.path.join('./news', ticker, date, title+'.txt')
# ๋ด์ซ ๋ฐ์ดํฐ ๊ฐ์ ธ์ค๊ธฐ
f = open(dir, 'r')
text = f.read()
f.close()
# ๋ชจ๋ธ ์ ์ฉ
answer = Tk_instruct(text, questions)
result = {}
result['answer'] = answer
return jsonify(result=result)
# Terminal : Flask : ์์ ํ๋ฉด ํฐ๋ฏธ๋ ์ฌ์คํ
# Elements : HTML : ์์ ํ๋ฉด ํฐ๋ฏธ๋ ์ฌ์คํ
# Console : javascript : ์ฌ์ดํธ ๋๊ธฐํ
# Sources : File : ์ฌ์ดํธ ๋๊ธฐํ
# CSS : ์ฌ์ดํธ ๋๊ธฐํ
if __name__ == "__main__":
# run app
# host : ๋ชจ๋ IP์ ๋ํด ์ ๊ทผ ํ์ฉ, ( Default. localhost = 127.0.0.1 )
# port : ์ ์์ open๋ http port, ( Default. port = 5000 )
app.run(host='0.0.0.0', port='7860') #http://0.0.0.0:5001
# app.run(debug=True) #http://0.0.0.0:5001 |