-
Notifications
You must be signed in to change notification settings - Fork 1
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #35 from sketch-talk/dev/BE
๋ฐฑ์๋ ์ผ๊ธฐ ์ ์ฅ ๋ฐ ๋ก๋ ๊ตฌํ
- Loading branch information
Showing
2 changed files
with
155 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
|
||
# ignore all files in any directory named temp | ||
api_key/ | ||
testver/ | ||
test_images/ | ||
__pycache__/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,149 @@ | ||
from fastapi import FastAPI, HTTPException | ||
from pydantic import BaseModel | ||
import openai | ||
import json | ||
import uuid | ||
from fastapi import File, UploadFile | ||
from fastapi.responses import JSONResponse | ||
from sqlalchemy import create_engine, Column, String, Integer, Date | ||
from sqlalchemy.orm import sessionmaker | ||
from sqlalchemy.ext.declarative import declarative_base | ||
import os | ||
import requests | ||
from fastapi.middleware.cors import CORSMiddleware | ||
from datetime import datetime | ||
import io | ||
from PIL import Image | ||
|
||
# api key ๋ถ๋ฌ์ค๊ธฐ | ||
with open("secrets.json") as config_file: | ||
config_data = json.load(config_file) | ||
print(config_data) | ||
OPENAI_API_KEY = config_data["openai_api_key"] | ||
HUG_API_KEY=config_data["hug_api_key"] | ||
|
||
# # ์ด๋ฏธ์ง ํ์ผ ์ ์ฅ ๊ฒฝ๋ก | ||
IMAGE_STORAGE_PATH = "/home/ubuntu/img/" | ||
#IMAGE_STORAGE_PATH="/Users/ss3un9/fastapi/test_images/" | ||
|
||
|
||
openai.api_key = OPENAI_API_KEY | ||
|
||
with open("db.json") as secret_file: | ||
secret_data = json.load(secret_file) | ||
db_user = secret_data["db_user"] | ||
db_password = secret_data["db_password"] | ||
db_host = secret_data["db_host"] | ||
db_name = secret_data["db_name"] | ||
|
||
app = FastAPI() | ||
|
||
# MySQL ์ฐ๊ฒฐ ๋ฌธ์์ด ์์ฑ | ||
SQLALCHEMY_DATABASE_URL = f"mysql://{db_user}:{db_password}@{db_host}/{db_name}" | ||
# ๋ฐ์ดํฐ๋ฒ ์ด์ค ์์ง ๋ฐ ์ธ์ ์ค์ | ||
engine = create_engine(SQLALCHEMY_DATABASE_URL) | ||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) | ||
Base = declarative_base() | ||
|
||
class Data(Base): | ||
__tablename__ = "data" | ||
|
||
no = Column(Integer, primary_key=True, autoincrement=True) | ||
date = Column(Date) # ๋ ์ง ์ปฌ๋ผ ์ถ๊ฐ | ||
title = Column(String) | ||
weather = Column(String) | ||
contents = Column(String) | ||
img_location = Column(String) | ||
|
||
#CORS | ||
origins = [ | ||
"*" | ||
] | ||
|
||
app.add_middleware( | ||
CORSMiddleware, | ||
allow_origins=origins, | ||
allow_credentials=True, # cookie ํฌํจ ์ฌ๋ถ๋ฅผ ์ค์ ํ๋ค. ๊ธฐ๋ณธ์ False | ||
allow_methods=["*"], # ํ์ฉํ method๋ฅผ ์ค์ ํ ์ ์์ผ๋ฉฐ, ๊ธฐ๋ณธ๊ฐ์ 'GET'์ด๋ค. | ||
allow_headers=["*"], # ํ์ฉํ http header ๋ชฉ๋ก์ ์ค์ ํ ์ ์์ผ๋ฉฐ Content-Type, Accept, Accept-Language, Content-Language์ ํญ์ ํ์ฉ๋๋ค. | ||
) | ||
|
||
class QuestionInput(BaseModel): | ||
title: str | ||
weather: str | ||
contents: str | ||
|
||
@app.post("/posts/save") | ||
async def get_answer(data: QuestionInput): | ||
title=data.title | ||
weather=data.weather | ||
contents=data.contents | ||
|
||
# GPT-3 ํธ์ถ (v1/chat/completions ์๋ํฌ์ธํธ ์ฌ์ฉ) | ||
response = openai.ChatCompletion.create( | ||
model="gpt-3.5-turbo", | ||
messages=[ | ||
{"role": "system", "content": "You are the assistant summarizing the sentence"}, | ||
{"role": "user", "content": f"{contents} \n Please translate the previous sentence into English"}, | ||
], | ||
|
||
temperature=0.5, | ||
) | ||
|
||
answer = response.choices[0].message["content"].strip() | ||
|
||
|
||
print(f"prompt : {answer}") #ํ๋กฌํํธ ์ถ๋ ฅ | ||
|
||
API_URL = "https://api-inference.huggingface.co/models/nerijs/pixel-art-xl" # ์ฌ์ฉ ๋ชจ๋ธ | ||
headers = {"Authorization": HUG_API_KEY} | ||
object_key_name = str(uuid.uuid4()) + '.jpg' # ๋๋ค์ด๋ฆ | ||
|
||
def query(payload): | ||
response = requests.post(API_URL, headers=headers, json=payload) | ||
return response.content | ||
|
||
image_bytes = query({ | ||
"inputs": answer, | ||
}) | ||
|
||
image = Image.open(io.BytesIO(image_bytes)) | ||
|
||
temp_file = IMAGE_STORAGE_PATH+object_key_name # ์ด๋ฏธ์ง๋ฅผ ์ ์ฅํ ๊ฒฝ๋ก ์ค์ | ||
image.save(temp_file) | ||
|
||
|
||
current_date = datetime.now().strftime("%Y-%m-%d") | ||
|
||
|
||
db = SessionLocal() | ||
db_entry = Data(title=title,date=current_date,weather=weather, contents=contents, img_location=object_key_name) | ||
db.add(db_entry) | ||
db.commit() | ||
db.refresh(db_entry) | ||
db.close() | ||
|
||
return {"image_name": f"static/{object_key_name}"} | ||
|
||
|
||
|
||
@app.get("/posts/result/{filename}") | ||
async def get_result(filename: str): | ||
# ๋ฐ์ดํฐ๋ฒ ์ด์ค์์ filename๊ณผ ์ผ์นํ๋ ํ ์กฐํ | ||
img_name=filename+".png" | ||
db = SessionLocal() | ||
data_entry = db.query(Data).filter_by(img_location=img_name).first() | ||
db.close() | ||
|
||
if data_entry: | ||
# ์กฐํ๋ ๋ฐ์ดํฐ๊ฐ ์๋ ๊ฒฝ์ฐ ๋ฐํ | ||
return { | ||
"date": data_entry.date.strftime("%Y-%m-%d"), | ||
"title": data_entry.title, | ||
"weather": data_entry.weather, | ||
"contents": data_entry.contents, | ||
"img_name": "static/" + data_entry.img_location, | ||
} | ||
else: | ||
# ๋ฐ์ดํฐ๊ฐ ์๋ ๊ฒฝ์ฐ ์๋ฌ ๋ฐํ | ||
raise HTTPException(status_code=404, detail="Data not found") |