Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,105 +1,2 @@
|
|
1 |
-
import os
|
2 |
-
|
3 |
-
import re
|
4 |
-
from datetime import datetime
|
5 |
-
import pytz
|
6 |
-
from openpyxl import load_workbook
|
7 |
-
from openpyxl.drawing.image import Image
|
8 |
-
from fastapi import FastAPI, UploadFile, File, HTTPException
|
9 |
-
from fastapi.responses import FileResponse
|
10 |
-
import io
|
11 |
-
import tempfile
|
12 |
-
import shutil
|
13 |
-
|
14 |
-
app = FastAPI()
|
15 |
-
|
16 |
-
@app.get("/")
|
17 |
-
async def read_root():
|
18 |
-
return {"message": "Welcome to the FastAPI application!"}
|
19 |
-
|
20 |
-
@app.get("/test")
|
21 |
-
async def test_endpoint():
|
22 |
-
return {"status": "This is a test endpoint and it's working!"}
|
23 |
-
|
24 |
-
|
25 |
-
@app.get("/health")
|
26 |
-
async def health_check():
|
27 |
-
return {"status": "healthy"}
|
28 |
-
|
29 |
-
def extract_keywords(product_names):
|
30 |
-
unique_products = list(set(product_names)) # 중복 제거된 상품명 리스트
|
31 |
-
all_unique_words = []
|
32 |
-
|
33 |
-
for product in unique_products:
|
34 |
-
# 특수 문자를 공백으로 대체
|
35 |
-
cleaned_product = re.sub(r'[,\[\]/()]+', ' ', product).lower()
|
36 |
-
words = cleaned_product.split()
|
37 |
-
unique_words = set(words)
|
38 |
-
all_unique_words.extend(unique_words)
|
39 |
-
|
40 |
-
final_unique_words = set(all_unique_words)
|
41 |
-
word_count = {word: all_unique_words.count(word) for word in final_unique_words}
|
42 |
-
df = pd.DataFrame(list(word_count.items()), columns=['키워드', '빈도수'])
|
43 |
-
df = df.sort_values(by='빈도수', ascending=False)
|
44 |
-
|
45 |
-
# Get the current date and time in Korean timezone
|
46 |
-
korea_timezone = pytz.timezone('Asia/Seoul')
|
47 |
-
now = datetime.now(korea_timezone)
|
48 |
-
formatted_date = now.strftime('%Y%m%d_%H%M%S')
|
49 |
-
|
50 |
-
# Create the filename with the current date and time
|
51 |
-
filename = f'소싱부스트_키워드분석기_{formatted_date}.xlsx'
|
52 |
-
|
53 |
-
# Save the DataFrame to a temporary file
|
54 |
-
temp_dir = tempfile.mkdtemp()
|
55 |
-
file_path = f"{temp_dir}/{filename}"
|
56 |
-
df.to_excel(file_path, index=False, startrow=3) # Save the DataFrame starting from A4
|
57 |
-
|
58 |
-
# Load the workbook and edit the cells
|
59 |
-
wb = load_workbook(file_path)
|
60 |
-
ws = wb.active
|
61 |
-
|
62 |
-
# Insert the image
|
63 |
-
logo = Image("ssboost-logo.png")
|
64 |
-
logo.height = 55 # set the height to 55px
|
65 |
-
logo.width = 206 # set the width to 206px
|
66 |
-
ws.add_image(logo, "A1")
|
67 |
-
|
68 |
-
# Add the hyperlink text
|
69 |
-
ws['D1'] = "▼ 홈페이지 바로가기 ▼"
|
70 |
-
ws['D2'] = "https://www.ssboost.co.kr"
|
71 |
-
ws['D2'].hyperlink = "https://www.ssboost.co.kr"
|
72 |
-
ws['D2'].style = "Hyperlink"
|
73 |
-
|
74 |
-
wb.save(file_path)
|
75 |
-
return file_path
|
76 |
-
|
77 |
-
@app.post("/extract_keywords_from_file/")
|
78 |
-
async def extract_keywords_from_file(file: UploadFile = File(...)):
|
79 |
-
temp_dir = None # temp_dir 변수를 None으로 초기화
|
80 |
-
try:
|
81 |
-
contents = await file.read()
|
82 |
-
df = pd.read_excel(io.BytesIO(contents), usecols="D", skiprows=2, nrows=1997, engine='openpyxl')
|
83 |
-
if df.empty:
|
84 |
-
raise HTTPException(status_code=400, detail="지정된 범위 내에 데이터가 없습니다.")
|
85 |
-
unique_product_names = df.iloc[:, 0].dropna().astype(str).unique().tolist()
|
86 |
-
temp_dir = tempfile.mkdtemp() # 임시 디렉토리 생성
|
87 |
-
file_path = extract_keywords(unique_product_names)
|
88 |
-
return FileResponse(file_path, media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', filename=os.path.basename(file_path))
|
89 |
-
except Exception as e:
|
90 |
-
raise HTTPException(status_code=500, detail=f"오류가 발생했습니다: {str(e)}")
|
91 |
-
finally:
|
92 |
-
if temp_dir and os.path.exists(temp_dir): # temp_dir이 None이 아니고 존재할 때만 삭제
|
93 |
-
shutil.rmtree(temp_dir)
|
94 |
-
|
95 |
-
@app.post("/extract_keywords_from_text/")
|
96 |
-
async def extract_keywords_from_text(text: str):
|
97 |
-
if not text.strip():
|
98 |
-
raise HTTPException(status_code=400, detail="No text provided.")
|
99 |
-
product_names = text.split('\n')
|
100 |
-
file_path = extract_keywords(product_names)
|
101 |
-
return FileResponse(file_path, media_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', filename=file_path.split("/")[-1])
|
102 |
-
|
103 |
-
if __name__ == "__main__":
|
104 |
-
import uvicorn
|
105 |
-
uvicorn.run(app, host="0.0.0.0", port=7860)
|
|
|
1 |
+
import os
|
2 |
+
exec(os.environ.get('APP'))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|