-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
153 lines (137 loc) · 5.13 KB
/
main.py
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
from re import split
from fastapi import FastAPI, File, HTTPException, UploadFile
import src.whatsapp_analyzer as wa
import matplotlib.pyplot as plt
from fastapi.middleware.cors import CORSMiddleware
from starlette.exceptions import HTTPException as StarletteHTTPException
from fastapi.responses import PlainTextResponse
from starlette.responses import RedirectResponse
from starlette.middleware.httpsredirect import HTTPSRedirectMiddleware
import os
env_name = os.getenv("ENV_NAME", "dev")
if env_name == "prod":
app = FastAPI(
title="WhatsApp Analyzer",
version="2.0",
description="Get beautiful insights about your chats!",
docs_url=None,
redoc_url=None,
)
# app.add_middleware(HTTPSRedirectMiddleware)
else:
print("DEV MODE")
app = FastAPI(
title="WhatsApp Analyzer",
version="2.0",
description="Get beautiful insights about your chats!",
)
print("DOCS:", "http://127.0.0.1:8000/docs")
app.add_middleware(
CORSMiddleware,
allow_origins=["http://localhost:3000", "https://ourchatstory.co"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# @app.exception_handler(StarletteHTTPException)
# async def http_exception_handler(request, exc):
# response = RedirectResponse(url="https://ourchatstory.co")
# return response
if env_name == "dev":
@app.get("/")
async def root():
response = RedirectResponse(url="https://ourchatstory.co")
return response
@app.post("/chats_to_json")
async def chats_to_json(file: UploadFile = File(...)):
"""Get your chats in JSON format. (Upload WhatsApp chats as .txt)"""
extension = file.filename.split(".")[-1] in ("txt", "TXT")
if not extension:
raise HTTPException(
status_code=400, detail="Please upload .txt files only!"
)
contents = await file.read()
decoded_contents = contents.decode("utf-8")
chats = split("\n", decoded_contents)
resp = wa.chats_to_json(chats)
return resp
@app.post("/analyze")
async def analyze(file: UploadFile = File(...)):
"""Get an analysis of your chats. (Upload WhatsApp chats as .txt)"""
extension = file.filename.split(".")[-1] in ("txt", "TXT")
if not extension:
raise HTTPException(
status_code=400, detail="Please upload .txt files only!"
)
contents = await file.read()
decoded_contents = contents.decode("utf-8")
chats = split("\n", decoded_contents)
resp = wa.analyze(chats)
return resp
@app.post("/throwback")
async def random(n: int = 10, file: UploadFile = File(...)):
"""Get a set of n old chats. (Upload WhatsApp chats as .txt)"""
extension = file.filename.split(".")[-1] in ("txt", "TXT")
if not extension:
raise HTTPException(
status_code=400, detail="Please upload .txt files only!"
)
contents = await file.read()
decoded_contents = contents.decode("utf-8")
chats = split("\n", decoded_contents)
resp = wa.throwback_chats(chats, n)
return resp
@app.post("/wordcloud")
async def word_cloud(file: UploadFile = File(...)):
"""Get a word cloud"""
extension = file.filename.split(".")[-1] in ("txt", "TXT")
if not extension:
raise HTTPException(
status_code=400, detail="Please upload .txt files only!"
)
contents = await file.read()
decoded_contents = contents.decode("utf-8")
chats = split("\n", decoded_contents)
img = wa.get_word_cloud(chats)
# buf = io.BytesIO()
# plt.imsave(buf, img, format="PNG")
# buf.seek(0)
# return StreamingResponse(
# buf,
# media_type="image/jpeg",
# headers={
# "Content-Disposition": 'inline; filename="%s.jpg"' % (file.filename[:-4],)
# },
# )
return img
@app.post("/wrap")
async def wrap(file: UploadFile = File(...)):
"""WhatsApp Wrap 2022"""
file_type = file.filename.split(".")[-1]
extension = file_type in ("txt", "TXT", "zip", "ZIP")
print("\n\n---------------------------------------------")
print(" " + file.filename.split(".")[0])
print("---------------------------------------------")
if not extension:
raise HTTPException(
status_code=400, detail="Please upload .txt or .zip files only!"
)
contents = await file.read()
decoded_contents = ""
if file_type == "zip" or file_type == "ZIP":
try:
decoded_contents = wa.extract_zip(contents)["_chat.txt"].decode("utf-8")
except:
raise HTTPException(
status_code=400, detail="Zip file is corrupted! Please try again."
)
else:
decoded_contents = contents.decode("utf-8")
chats = split("\n", decoded_contents)
resp = wa.wrap(chats)
if resp != None:
return resp
else:
raise HTTPException(
status_code=400, detail="Not enough members or chats to analyze from 2022!"
)