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