Skip to content

Commit

Permalink
Merge pull request #35 from sketch-talk/dev/BE
Browse files Browse the repository at this point in the history
๋ฐฑ์—”๋“œ ์ผ๊ธฐ ์ €์žฅ ๋ฐ ๋กœ๋“œ ๊ตฌํ˜„
  • Loading branch information
ss3un9 authored Nov 1, 2023
2 parents 4d92cb4 + ed177db commit 67e1a2b
Show file tree
Hide file tree
Showing 2 changed files with 155 additions and 0 deletions.
6 changes: 6 additions & 0 deletions .gitignore
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__/
149 changes: 149 additions & 0 deletions backend/main1_4.py
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")

0 comments on commit 67e1a2b

Please sign in to comment.