-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.py
More file actions
186 lines (134 loc) · 4.71 KB
/
Copy pathapp.py
File metadata and controls
186 lines (134 loc) · 4.71 KB
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
import os
from flask import Flask, render_template, request, jsonify, send_from_directory
from bs4 import BeautifulSoup
import requests
import json
import re
import openai
import dotenv
dotenv.load_dotenv()
app = Flask(__name__)
@app.route('/', defaults={'path': ''})
@app.route('/<path:path>')
def serveReactApp(path):
print(path)
if path.startswith('api/') or path.startswith('static/'):
return app.send_static_file(path)
# Use the correct MIME types for JavaScript and CSS files
if path.endswith('.js'):
return send_from_directory('templates', path, mimetype='application/javascript')
elif path.endswith('.css'):
return send_from_directory('templates', path, mimetype='text/css')
elif path.endswith('.svg'):
return send_from_directory('templates', path, mimetype='image/svg+xml')
else:
print("Queued website")
return send_from_directory('templates/', 'index.html')
@app.route('/initialize', methods = ["POST"])
def initialize():
data = request.form
input = data['input']
#gets the link and book name from the first search result
search_query = input
url = f'https://www.sparknotes.com/search?q={search_query}'
print(f"searching for {search_query}...")
response = requests.get(url)
html_content = response.content
print(f'grabbing search results...')
soup = BeautifulSoup(html_content, 'html.parser')
search_results = soup.find(class_="search-result-block top-result lit-search-icon")
if search_results == None:
print("no results")
return jsonify({})
link = search_results.find('a').get('href')
name = search_results.find('h3').text.strip().rsplit(' ', 2)[0]
print(f'name found: {name}')
#now needs to get the chapters
url = f'https://www.sparknotes.com{link}'
print('searching for chapters...')
response = requests.get(url)
html_content = response.content
soup = BeautifulSoup(html_content, 'html.parser')
chapters = {}
chapters["Entire book"] = link + "summary/"
#getting the links for the chapters
indiv_chapters = soup.find_all(class_="landing-page__umbrella__link")
pattern = r'/section(\d+)/$'
for div in indiv_chapters:
if re.search(pattern, div.get('href')):
chapters[div.text.strip()] = div.get('href')
print('chapters found')
info = {
"name": name,
"link": link,
"chapters": chapters,
}
return jsonify(info)
#generation part
print('trying openai key...')
openai.api_key = os.environ.get('API_KEY')
print('openai key works')
#input format
"""
{
name: {name},
link: {link},
chapter: {chapter},
chapterlink: {link of chapter},
}
"""
@app.route('/generate', methods = ["POST"])
def generate():
print('pulling data...')
data = request.form
name = data['name']
chapter = data['chapter']
chapterlink = data['chapterLink']
print(f'data received for {name}, {chapter}:)')
#get the chapter text
print('getting book content...')
url = f"https://www.sparknotes.com{chapterlink}"
response = requests.get(url)
html_content = response.content
print('content received')
soup = BeautifulSoup(html_content, 'html.parser')
try:
summarydiv = soup.find(class_='mainTextContent main-container')
paragraphs = summarydiv.find_all('p')
content = ""
for paragraph in paragraphs:
content += re.sub(r'\s+', ' ', paragraph.text) + '\n'
print('content formatted via 1')
except:
try:
summarydiv = soup.find(class_="studyGuideText")
paragraphs = summarydiv.find_all('p')
content = ""
for paragraph in paragraphs:
content+=re.sub(r'\s+', ' ', paragraph.text) + '\n'
print('content formatted via 2')
except:
return jsonify({"error": "no summary found"})
with open('instruction.txt', 'r') as file:
instruction = file.read()
summaryPrompt = f"""
The user is reading the book {name}, {chapter}. You are to generate 10 questions based off of the summary below.
Summary:
{content}
"""
messages = [{"role": "system", "content": instruction}, {"role": "system", "content": summaryPrompt}]
print("generating questions...")
try:
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo",
messages=messages
)
result = response["choices"][0]["message"]["content"]
print(result)
questions_data = json.loads(result, strict=False)
return jsonify(questions_data)
except Exception as e:
print(e)
print('responses generated')
if __name__ == "__main__":
app.run(debug=True)