-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
335 lines (259 loc) · 8.79 KB
/
main.py
File metadata and controls
335 lines (259 loc) · 8.79 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
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
import os
import json
import hashlib
import base64
import logging
from urllib.parse import urlparse, urljoin
from datetime import datetime
import threading
from email.utils import formatdate
from flask import Flask, request, jsonify, g, send_file, Response, make_response, send_from_directory
from flask_cors import CORS
from flask_cors import cross_origin
import requests
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import padding
import mimetypes
import hashlib
from urllib.parse import urlsplit
import db
import init
from auth import require_auth
import ipaddress
import socket
app = Flask(__name__)
def parse_body(data):
try:
return json.loads(data)
except:
return {}
CORS(
app,
resources={r"/*": {"origins": "*"}},
supports_credentials=True,
allow_headers=["Content-Type", "Authorization"]
)
logging.basicConfig(level=logging.info)
CACHE_DIR = os.environ.get("CACHE_DIR")
UPLOADS_DIR = os.environ.get("UPLOADS_DIR")
os.makedirs(CACHE_DIR, exist_ok=True)
os.makedirs(UPLOADS_DIR, exist_ok=True)
PORT = os.environ.get("PORT")
DOMAIN = os.environ.get('DOMAIN')
API_KEY = os.environ.get("AI_API_KEY")
API_URL = os.environ.get('AI_API_URL')
AI_MODEL = os.environ.get('AI_MODEL')
system_prompt = """Hi! You are a summarizing assistant. Your job is to summarize the following text, no matter what it is about. Be concise, and keep the key points in the summary. You should be clear, and respond in the language the text is.
IMPORTANT: Your response MUST follow this exact format:
1. Start with a title prefixed with '# ' (markdown heading)
2. Press enter to go to a new line
3. Write your summary below the title
Example format:
# Summary Title Here
Your summary text goes here...
Now summarize this text:
"""
init.init()
def summarizeContent(content):
full_content = system_prompt + content
headers = {
"Authorization": f"Bearer {API_KEY}",
"Content-Type": "application/json"
}
data = {
"model": AI_MODEL,
"messages": [
{
"role": "user",
"content": full_content if isinstance(full_content, str) else str(full_content)
}
],
"temperature": 0.7
}
response = requests.post(API_URL + "/chat/completions", headers=headers, json=data)
if response.status_code == 200:
result = response.json()
return result.get('choices', [{}])[0].get('message', {}).get('content') or result.get('result') or result.get('text') or str(result)
else:
print(f"err {response.status_code}: {response.text}")
return None
#routes
@app.route("/login", methods=['POST'])
def login():
body = parse_body(request.data)
username = body.get('username') # get post username param
password = body.get('password') # get post password param
if not username or not password:
return jsonify({"error": "username and password are required"}), 400
session = db.login(username, password)
if not session:
return jsonify({"error": "invalid credentials"}), 401
return jsonify({"token": session.get("token"), "expires_at": session.get("expires_at")})
from flask import jsonify, request
@app.route("/updateAccount", methods=['POST'])
@require_auth
def updAcc():
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Bearer "):
return jsonify({"error": "Token required"}), 401
token = auth_header[7:]
user_data = db.authenticate(token)
if not user_data:
return jsonify({"error": "Invalid token"}), 401
body = parse_body(request.data)
new_username = body.get('username')
old_password = body.get('old_password')
new_password = body.get('new_password')
new_email = body.get('email')
user_id = user_data.get('id')
if new_username:
db.update_username(user_id, new_username)
if old_password and new_password:
if db.verify_password(user_id, old_password):
db.update_password(user_id, new_password)
else:
return jsonify({"error": "Old password is incorrect"}), 401
if new_email:
db.update_email(user_id, new_email)
updated_user_data = db.get_user_by_id(user_id)
return jsonify(updated_user_data), 200
@app.route("/me", methods=["GET"])
@require_auth
def me():
auth_header = request.headers.get("Authorization")
if auth_header and auth_header.startswith("Bearer "):
token = auth_header[7:] # remove "bearer "
else:
return "token required", 404
user_data = db.authenticate(token)
return jsonify(user_data)
@app.route("/summarize", methods=["POST", "OPTIONS"])
@cross_origin()
@require_auth
def summarize():
if request.method == "OPTIONS":
return "", 200
body = parse_body(request.data)
content = body.get('content')
if not content or not isinstance(content, str):
return jsonify({"error": "content is required and must be a string"}), 400
summarized = summarizeContent(content)
response = {
"success": "true",
"summary": summarized,
"model": AI_MODEL
}
return jsonify(response)
@app.route("/saveSummary", methods=["POST", "OPTIONS"])
@cross_origin()
@require_auth
def saveSummary():
if request.method == "OPTIONS":
return "", 200
auth_header = request.headers.get("Authorization")
if auth_header and auth_header.startswith("Bearer "):
token = auth_header[7:] # remove "bearer "
else:
return "token required", 404
body = parse_body(request.data)
title = body.get('title')
summary = body.get('summary')
userId = db.authenticate(token)["id"]
success = db.saveSummary(title, summary, userId)
response = {
"result": success
}
return jsonify(response)
@app.route("/getSummaries", methods=["POST", "OPTIONS"])
@cross_origin()
@require_auth
def getSummaries():
if request.method == "OPTIONS":
return "", 200
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Bearer "):
return jsonify({"error": "Token required"}), 401
token = auth_header[7:] # remove "Bearer "
user = db.authenticate(token)
if not user:
return jsonify({"error": "Invalid token"}), 401
userId = user["id"]
summaries = db.getSummariesByUser(userId)
if not summaries:
return jsonify({"summaries": []}), 200
response = {
"success": "true",
"summaries": [
{
"id": s["id"],
"title": s["title"],
"summary": s["summary"],
"createdAt": s["createdAt"]
}
for s in summaries
]
}
return jsonify(response), 200
@app.route("/summary/<sid>", methods=["POST", "OPTIONS"])
@cross_origin()
@require_auth
def getSummary(sid):
if request.method == "OPTIONS":
return "", 200
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Bearer "):
return jsonify({"error": "Token required"}), 401
token = auth_header[7:] # remove "Bearer "
user = db.authenticate(token)
if not user:
return jsonify({"error": "Invalid token"}), 401
userId = user["id"]
summary = db.getSummary(sid)
if not userId == summary["userId"]:
return
response = {
"success": "true",
"summary": {
"id": summary["id"],
"title": summary["title"],
"summary": summary["summary"],
"createdAt": summary["createdAt"]
}
}
return jsonify(response), 200
@app.route("/summary/delete/<sid>", methods=["POST", "OPTIONS"])
@cross_origin()
@require_auth
def delSummary(sid):
if request.method == "OPTIONS":
return "", 200
auth_header = request.headers.get("Authorization")
if not auth_header or not auth_header.startswith("Bearer "):
return jsonify({"error": "Token required"}), 401
token = auth_header[7:] # remove "Bearer "
user = db.authenticate(token)
if not user:
return jsonify({"error": "Invalid token"}), 401
userId = user["id"]
summary = db.getSummary(sid)
if not userId == summary["userId"]:
return
result = db.deleteSummary(sid)
if result:
response = {
"success": "true",
}
else:
response = {
"success": "false",
}
return jsonify(response), 200
@app.route("/", methods=['GET'])
def index():
return send_from_directory("www", "index.html")
@app.route("/<path:filename>")
def serve_static(filename):
return send_from_directory("www", filename)
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5001)