Skip to content

Commit 67e1a2b

Browse files
authored
Merge pull request #35 from sketch-talk/dev/BE
백엔드 일기 저장 및 로드 구현
2 parents 4d92cb4 + ed177db commit 67e1a2b

File tree

2 files changed

+155
-0
lines changed

2 files changed

+155
-0
lines changed

.gitignore

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
2+
# ignore all files in any directory named temp
3+
api_key/
4+
testver/
5+
test_images/
6+
__pycache__/

backend/main1_4.py

Lines changed: 149 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,149 @@
1+
from fastapi import FastAPI, HTTPException
2+
from pydantic import BaseModel
3+
import openai
4+
import json
5+
import uuid
6+
from fastapi import File, UploadFile
7+
from fastapi.responses import JSONResponse
8+
from sqlalchemy import create_engine, Column, String, Integer, Date
9+
from sqlalchemy.orm import sessionmaker
10+
from sqlalchemy.ext.declarative import declarative_base
11+
import os
12+
import requests
13+
from fastapi.middleware.cors import CORSMiddleware
14+
from datetime import datetime
15+
import io
16+
from PIL import Image
17+
18+
# api key 불러오기
19+
with open("secrets.json") as config_file:
20+
config_data = json.load(config_file)
21+
print(config_data)
22+
OPENAI_API_KEY = config_data["openai_api_key"]
23+
HUG_API_KEY=config_data["hug_api_key"]
24+
25+
# # 이미지 파일 저장 경로
26+
IMAGE_STORAGE_PATH = "/home/ubuntu/img/"
27+
#IMAGE_STORAGE_PATH="/Users/ss3un9/fastapi/test_images/"
28+
29+
30+
openai.api_key = OPENAI_API_KEY
31+
32+
with open("db.json") as secret_file:
33+
secret_data = json.load(secret_file)
34+
db_user = secret_data["db_user"]
35+
db_password = secret_data["db_password"]
36+
db_host = secret_data["db_host"]
37+
db_name = secret_data["db_name"]
38+
39+
app = FastAPI()
40+
41+
# MySQL 연결 문자열 생성
42+
SQLALCHEMY_DATABASE_URL = f"mysql://{db_user}:{db_password}@{db_host}/{db_name}"
43+
# 데이터베이스 엔진 및 세션 설정
44+
engine = create_engine(SQLALCHEMY_DATABASE_URL)
45+
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
46+
Base = declarative_base()
47+
48+
class Data(Base):
49+
__tablename__ = "data"
50+
51+
no = Column(Integer, primary_key=True, autoincrement=True)
52+
date = Column(Date) # 날짜 컬럼 추가
53+
title = Column(String)
54+
weather = Column(String)
55+
contents = Column(String)
56+
img_location = Column(String)
57+
58+
#CORS
59+
origins = [
60+
"*"
61+
]
62+
63+
app.add_middleware(
64+
CORSMiddleware,
65+
allow_origins=origins,
66+
allow_credentials=True, # cookie 포함 여부를 설정한다. 기본은 False
67+
allow_methods=["*"], # 허용할 method를 설정할 수 있으며, 기본값은 'GET'이다.
68+
allow_headers=["*"], # 허용할 http header 목록을 설정할 수 있으며 Content-Type, Accept, Accept-Language, Content-Language은 항상 허용된다.
69+
)
70+
71+
class QuestionInput(BaseModel):
72+
title: str
73+
weather: str
74+
contents: str
75+
76+
@app.post("/posts/save")
77+
async def get_answer(data: QuestionInput):
78+
title=data.title
79+
weather=data.weather
80+
contents=data.contents
81+
82+
# GPT-3 호출 (v1/chat/completions 엔드포인트 사용)
83+
response = openai.ChatCompletion.create(
84+
model="gpt-3.5-turbo",
85+
messages=[
86+
{"role": "system", "content": "You are the assistant summarizing the sentence"},
87+
{"role": "user", "content": f"{contents} \n Please translate the previous sentence into English"},
88+
],
89+
90+
temperature=0.5,
91+
)
92+
93+
answer = response.choices[0].message["content"].strip()
94+
95+
96+
print(f"prompt : {answer}") #프롬프트 출력
97+
98+
API_URL = "https://api-inference.huggingface.co/models/nerijs/pixel-art-xl" # 사용 모델
99+
headers = {"Authorization": HUG_API_KEY}
100+
object_key_name = str(uuid.uuid4()) + '.jpg' # 랜덤이름
101+
102+
def query(payload):
103+
response = requests.post(API_URL, headers=headers, json=payload)
104+
return response.content
105+
106+
image_bytes = query({
107+
"inputs": answer,
108+
})
109+
110+
image = Image.open(io.BytesIO(image_bytes))
111+
112+
temp_file = IMAGE_STORAGE_PATH+object_key_name # 이미지를 저장할 경로 설정
113+
image.save(temp_file)
114+
115+
116+
current_date = datetime.now().strftime("%Y-%m-%d")
117+
118+
119+
db = SessionLocal()
120+
db_entry = Data(title=title,date=current_date,weather=weather, contents=contents, img_location=object_key_name)
121+
db.add(db_entry)
122+
db.commit()
123+
db.refresh(db_entry)
124+
db.close()
125+
126+
return {"image_name": f"static/{object_key_name}"}
127+
128+
129+
130+
@app.get("/posts/result/{filename}")
131+
async def get_result(filename: str):
132+
# 데이터베이스에서 filename과 일치하는 행 조회
133+
img_name=filename+".png"
134+
db = SessionLocal()
135+
data_entry = db.query(Data).filter_by(img_location=img_name).first()
136+
db.close()
137+
138+
if data_entry:
139+
# 조회된 데이터가 있는 경우 반환
140+
return {
141+
"date": data_entry.date.strftime("%Y-%m-%d"),
142+
"title": data_entry.title,
143+
"weather": data_entry.weather,
144+
"contents": data_entry.contents,
145+
"img_name": "static/" + data_entry.img_location,
146+
}
147+
else:
148+
# 데이터가 없는 경우 에러 반환
149+
raise HTTPException(status_code=404, detail="Data not found")

0 commit comments

Comments
 (0)