first commit

This commit is contained in:
bluebamus committed 2025-12-19 09:36:23 +09:00
commit 1ff70c7925
71 files changed
+4175

No files matched your search

View File
Whitespace-only changes.
View File
Whitespace-only changes.
+135
View File
@@ -0,0 +1,135 @@
from sqladmin import ModelView
from app.lyrics.models import PromptTemplate # noqa: F401
from app.lyrics.models import Attribute, SongResultsAll, SongSample, StoreDefaultInfo
class LyricsStoreDefaultInfoAdmin(ModelView, model=StoreDefaultInfo):
name = "상가 기본 정보"
name_plural = "상가 정보 목록"
icon = "fa-solid fa-store"
category = "상가 정보 관리"
page_size = 20
column_list = ["id", "store_name"]
# 폼(생성/수정)에서 제외
form_excluded_columns = ["created_at"]
column_searchable_list = [
StoreDefaultInfo.store_name,
StoreDefaultInfo.store_phone_number,
]
column_default_sort = (StoreDefaultInfo.store_name, False) # False: ASC, True: DESC
column_sortable_list = [
StoreDefaultInfo.created_at,
StoreDefaultInfo.store_phone_number,
]
# 폼 컬럼 (기존 유지, user_posts가 관계라면 모델에 정의 필요)
# form_columns = [
# Post.user_id,
# Post.title,
# Post.content,
# Post.is_published,
# Post.user_posts, # Many-to-Many 또는 One-to-Many 관계 가정
# ]
class LyricsAttributeAdmin(ModelView, model=Attribute):
name = "속성"
name_plural = "속성 목록"
icon = "fa-solid fa-tags"
category = "속성 관리"
page_size = 20
column_list = ["id", "attr_category"]
# 폼(생성/수정)에서 제외
form_excluded_columns = ["created_at"]
column_searchable_list = [
Attribute.attr_category,
Attribute.attr_value,
]
column_default_sort = (Attribute.created_at, False) # False: ASC, True: DESC
column_sortable_list = [
Attribute.created_at,
]
class LyricsSongSampleAdmin(ModelView, model=SongSample):
name = "가사 샘플"
name_plural = "가사 샘플 목록"
icon = "fa-solid fa-flask"
category = "가사 샘플 관리"
page_size = 20
column_list = [
"id",
"ai_model",
"season",
"num_of_people",
"people_category",
"genre",
]
# 폼(생성/수정)에서 제외
form_excluded_columns = ["created_at"]
column_default_sort = (SongSample.created_at, False) # False: ASC, True: DESC
class LyricsPromptTemplateAdmin(ModelView, model=PromptTemplate):
name = "프롬프트 템플릿"
name_plural = "프롬프트 템플릿 목록"
icon = "fa-solid fa-file-alt"
category = "프롬프트 템플릿 관리"
page_size = 20
column_list = [
"id",
"description",
]
# 폼(생성/수정)에서 제외
form_excluded_columns = ["created_at"]
column_default_sort = (PromptTemplate.created_at, False) # False: ASC, True: DESC
class LyricsSongResultsAllAdmin(ModelView, model=SongResultsAll):
name = "가사 결과"
name_plural = "가사 결과 목록"
icon = "fa-solid fa-music"
category = "가사 결과 관리"
page_size = 20
column_list = [
"id",
"store_name",
]
# 폼(생성/수정)에서 제외
form_excluded_columns = ["created_at"]
column_searchable_list = [
SongResultsAll.ai,
SongResultsAll.ai_model,
]
column_default_sort = (SongResultsAll.created_at, False) # False: ASC, True: DESC
column_sortable_list = [
SongResultsAll.store_name,
SongResultsAll.store_category,
SongResultsAll.ai,
SongResultsAll.ai_model,
SongResultsAll.num_of_people,
SongResultsAll.genre,
SongResultsAll.created_at,
]
View File
Whitespace-only changes.
Whitespace-only changes.
+146
View File
@@ -0,0 +1,146 @@
from typing import Any
from fastapi import APIRouter, Depends, Request # , UploadFile, File, status
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.session import get_session
from app.lyrics.services import lyrics
router = APIRouter(prefix="/lyrics", tags=["lyrics"])
@router.get("/store")
async def home(
request: Request,
conn: AsyncSession = Depends(get_session),
):
# store_info_list: List[StoreData] = await lyrics_svc.get_store_info(conn)
result: Any = await lyrics.get_store_info(conn)
# return templates.TemplateResponse(
# request=request,
# name="store.html",
# context={"store_info_list": result},
# )
pass
@router.post("/attributes")
async def attribute(
request: Request,
conn: AsyncSession = Depends(get_session),
):
print("attributes")
print(await request.form())
result: Any = await lyrics.get_attribute(conn)
print(result)
# return templates.TemplateResponse(
# request=request,
# name="attribute.html",
# context={
# "attribute_group_dict": result,
# "before_dict": await request.form(),
# },
# )
pass
@router.post("/fewshot")
async def sample_song(
request: Request,
conn: AsyncSession = Depends(get_session),
):
print("fewshot")
print(await request.form())
result: Any = await lyrics.get_sample_song(conn)
print(result)
# return templates.TemplateResponse(
# request=request,
# name="fewshot.html",
# context={"fewshot_list": result, "before_dict": await request.form()},
# )
pass
@router.post("/prompt")
async def prompt_template(
request: Request,
conn: AsyncSession = Depends(get_session),
):
print("prompt_template")
print(await request.form())
result: Any = await lyrics.get_prompt_template(conn)
print(result)
print("prompt_template after")
print(await request.form())
# return templates.TemplateResponse(
# request=request,
# name="prompt.html",
# context={"prompt_list": result, "before_dict": await request.form()},
# )
pass
@router.post("/result")
async def song_result(
request: Request,
conn: AsyncSession = Depends(get_session),
):
print("song_result")
print(await request.form())
result: Any = await lyrics.make_song_result(request, conn)
print("result : ", result)
# return templates.TemplateResponse(
# request=request,
# name="result.html",
# context={"result_dict": result},
# )
pass
@router.get("/result")
async def get_song_result(
request: Request,
conn: AsyncSession = Depends(get_session),
):
print("get_song_result")
print(await request.form())
result: Any = await lyrics.get_song_result(conn)
print("result : ", result)
# return templates.TemplateResponse(
# request=request,
# name="result.html",
# context={"result_dict": result},
# )
pass
@router.post("/automation")
async def automation(
request: Request,
conn: AsyncSession = Depends(get_session),
):
print("automation")
print(await request.form())
result: Any = await lyrics.make_automation(request, conn)
print("result : ", result)
# return templates.TemplateResponse(
# request=request,
# name="result.html",
# context={"result_dict": result},
# )
pass
View File
Whitespace-only changes.
+8
View File
@@ -0,0 +1,8 @@
from typing import Annotated
from fastapi import Depends
from sqlalchemy.ext.asyncio import AsyncSession
from app.database.session import get_session
SessionDep = Annotated[AsyncSession, Depends(get_session)]
+158
View File
@@ -0,0 +1,158 @@
from app.core.database import Base
from sqlalchemy import (
Boolean,
DateTime,
Enum,
ForeignKey,
Index,
Integer,
PrimaryKeyConstraint,
String,
func,
)
from sqlalchemy.orm import Mapped, mapped_column, relationship
from starlette.authentication import BaseUser
class User(Base, BaseUser):
__tablename__ = "users"
id: Mapped[int] = mapped_column(
Integer, primary_key=True, nullable=False, autoincrement=True
)
username: Mapped[str] = mapped_column(
String(255), unique=True, nullable=False, index=True
)
email: Mapped[str] = mapped_column(
String(255), unique=True, nullable=False, index=True
)
hashed_password: Mapped[str] = mapped_column(String(60), nullable=False)
# age_level 컬럼을 Enum으로 정의
age_level_choices = ["10", "20", "30", "40", "50", "60", "70", "80"]
age_level: Mapped[str] = mapped_column(
Enum(*age_level_choices, name="age_level_enum"),
nullable=False,
default="10",
)
is_active: Mapped[bool] = mapped_column(Boolean, default=True)
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
# One-to-many relationship with Post (DynamicMapped + lazy="dynamic")
posts_user: Mapped[list["Post"]] = relationship("Post", back_populates="user_posts")
# # Many-to-many relationship with Group
# user_groups: DynamicMapped["UserGroupAssociation"] = relationship(
# "UserGroupAssociation", back_populates="user", lazy="dynamic"
# )
# n:m 관계 (Group) – 최적의 lazy 옵션: selectin
group_user: Mapped[list["Group"]] = relationship(
"Group",
secondary="user_group_association",
back_populates="user_group",
lazy="selectin",
)
def __repr__(self) -> str:
return f"id={self.id}, username={self.username}"
@property
def is_authenticated(self) -> bool:
return self.is_active
@property
def display_name(self) -> str:
return self.username
@property
def identity(self) -> str:
return self.username
# 1:N Relationship - Posts
class Post(Base):
__tablename__ = "posts"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
user_id: Mapped[int] = mapped_column(
Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False
)
title: Mapped[str] = mapped_column(String(255), nullable=False)
content: Mapped[str] = mapped_column(String(10000), nullable=False)
is_published: Mapped[bool] = mapped_column(Boolean, default=False)
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
updated_at: Mapped[DateTime] = mapped_column(
DateTime, server_default=func.now(), onupdate=func.now()
)
# tags: Mapped[dict] = mapped_column(MutableDict.as_mutable(JSONB), default=[]) // sqlite 지원 안함
view_count: Mapped[int] = mapped_column(Integer, default=0)
# Many-to-one relationship with User (using dynamic loading)
user_posts: Mapped["User"] = relationship("User", back_populates="posts_user")
def __repr__(self) -> str:
return f"Post(id={self.id}, user_id={self.user_id}, title={self.title})"
__table_args__ = (
Index("idx_posts_user_id", "user_id"),
Index("idx_posts_created_at", "created_at"),
Index(
"idx_posts_user_id_created_at", "user_id", "created_at"
), # Composite index
)
# N:M Relationship - Users and Groups
# Association table for many-to-many relationship
# N:M Association Table (중간 테이블)
class UserGroupAssociation(Base):
__tablename__ = "user_group_association"
user_id: Mapped[int] = mapped_column(
Integer, ForeignKey("users.id", ondelete="CASCADE"), primary_key=True
)
group_id: Mapped[int] = mapped_column(
Integer, ForeignKey("groups.id", ondelete="CASCADE"), primary_key=True
)
# # 관계 정의
# user: Mapped["User"] = relationship("User", back_populates="user_groups")
# group: Mapped["Group"] = relationship("Group", back_populates="group_users")
# # 복합 기본 키 설정
# 기본 키 설정을 위한 __table_args__ 추가
__table_args__ = (PrimaryKeyConstraint("user_id", "group_id"),)
def __repr__(self) -> str:
return f"UserGroupAssociation(user_id={self.user_id}, group_id={self.group_id})"
# Group 테이블
class Group(Base):
__tablename__ = "groups"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
name: Mapped[str] = mapped_column(String(255), nullable=False, unique=True)
description: Mapped[str] = mapped_column(String(1000))
is_public: Mapped[bool] = mapped_column(Boolean, default=True)
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
updated_at: Mapped[DateTime] = mapped_column(
DateTime, server_default=func.now(), onupdate=func.now()
)
user_group: Mapped[list["User"]] = relationship(
"User",
secondary="user_group_association",
back_populates="group_user",
lazy="selectin",
)
# Group을 만든 사용자와 관계 (일반적인 1:N 관계)
def __repr__(self) -> str:
return f"Group(id={self.id}, name={self.name})"
__table_args__ = (
Index("idx_groups_name", "name"),
Index("idx_groups_is_public", "is_public"),
Index("idx_groups_created_at", "created_at"),
Index("idx_groups_composite", "is_public", "created_at"),
)
+273
View File
@@ -0,0 +1,273 @@
from sqlalchemy import DateTime, Integer, String, Text, func
from sqlalchemy.orm import Mapped, mapped_column
from app.database.session import Base
# from sqlalchemy import (
# Column,
# Integer,
# String,
# Boolean,
# DateTime,
# ForeignKey,
# Numeric,
# Table,
# Index,
# UniqueConstraint,
# CheckConstraint,
# text,
# func,
# PrimaryKeyConstraint,
# Enum,
# )
class StoreDefaultInfo(Base):
__tablename__ = "store_default_info"
id: Mapped[int] = mapped_column(
Integer, primary_key=True, nullable=False, autoincrement=True
)
store_info: Mapped[str] = mapped_column(
Text,
unique=False,
nullable=True,
)
store_name: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=False,
)
store_category: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=True,
)
store_region: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=True,
)
store_address: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=True,
)
store_phone_number: Mapped[str] = mapped_column(
String(255),
unique=True,
nullable=True,
)
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
def __repr__(self) -> str:
return f"id={self.id}, store_name={self.store_name}"
class PromptTemplate(Base):
__tablename__ = "prompt_template"
id: Mapped[int] = mapped_column(
Integer, primary_key=True, nullable=False, autoincrement=True
)
description: Mapped[str] = mapped_column(
Text,
unique=False,
nullable=True,
)
prompt: Mapped[str] = mapped_column(
Text,
unique=False,
nullable=False,
)
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
def __repr__(self) -> str:
return f"id={self.id}, description={self.description}"
class Attribute(Base):
__tablename__ = "attribute"
id: Mapped[int] = mapped_column(
Integer, primary_key=True, nullable=False, autoincrement=True
)
attr_category: Mapped[str] = mapped_column(
String(255),
unique=True,
nullable=False,
)
attr_value: Mapped[str] = mapped_column(
String(255),
unique=True,
nullable=False,
)
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
def __repr__(self) -> str:
return f"id={self.id}, attr_category={self.attr_category}"
class SongSample(Base):
__tablename__ = "song_sample"
id: Mapped[int] = mapped_column(
Integer, primary_key=True, nullable=False, autoincrement=True
)
ai: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=False,
)
ai_model: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=False,
)
genre: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=True,
)
sample_song: Mapped[str] = mapped_column(
Text,
unique=False,
nullable=False,
)
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
def __repr__(self) -> str:
return f"id={self.id}, sample_song={self.sample_song}"
class SongResultsAll(Base):
__tablename__ = "song_results_all"
id: Mapped[int] = mapped_column(
Integer, primary_key=True, nullable=False, autoincrement=True
)
store_info: Mapped[str] = mapped_column(
Text,
unique=False,
nullable=True,
)
store_name: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=False,
)
store_category: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=True,
)
store_address: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=True,
)
store_phone_number: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=True,
)
description: Mapped[str] = mapped_column(
Text,
unique=False,
nullable=True,
)
prompt: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=False,
)
attr_category: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=False,
)
attr_value: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=False,
)
ai: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=False,
)
ai_model: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=False,
)
season: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=True,
)
num_of_people: Mapped[int] = mapped_column(
Integer,
unique=False,
nullable=True,
)
people_category: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=True,
)
genre: Mapped[str] = mapped_column(
String(255),
unique=False,
nullable=True,
)
sample_song: Mapped[str] = mapped_column(
Text,
unique=False,
nullable=False,
)
result_song: Mapped[str] = mapped_column(
Text,
unique=False,
nullable=False,
)
created_at: Mapped[DateTime] = mapped_column(DateTime, server_default=func.now())
def __repr__(self) -> str:
return f"id={self.id}, result_song={self.result_song}"
View File
Whitespace-only changes.
+91
View File
@@ -0,0 +1,91 @@
from dataclasses import dataclass, field
from datetime import datetime
from typing import Dict, List
from fastapi import Request
@dataclass
class StoreData:
id: int
created_at: datetime
store_name: str
store_category: str | None = None
store_region: str | None = None
store_address: str | None = None
store_phone_number: str | None = None
store_info: str | None = None
@dataclass
class AttributeData:
id: int
attr_category: str
attr_value: str
created_at: datetime
@dataclass
class SongSampleData:
id: int
ai: str
ai_model: str
sample_song: str
season: str | None = None
num_of_people: int | None = None
people_category: str | None = None
genre: str | None = None
@dataclass
class PromptTemplateData:
id: int
prompt: str
description: str | None = None
@dataclass
class SongFormData:
store_name: str
store_id: str
prompts: str
attributes: Dict[str, str] = field(default_factory=dict)
attributes_str: str = ""
lyrics_ids: List[int] = field(default_factory=list)
llm_model: str = "gpt-4o"
@classmethod
async def from_form(cls, request: Request):
"""Request의 form 데이터로부터 dataclass 인스턴스 생성"""
form_data = await request.form()
# 고정 필드명들
fixed_keys = {"store_info_name", "store_id", "llm_model", "prompts"}
# lyrics-{id} 형태의 모든 키를 찾아서 ID 추출
lyrics_ids = []
attributes = {}
for key, value in form_data.items():
if key.startswith("lyrics-"):
lyrics_id = key.split("-")[1]
lyrics_ids.append(int(lyrics_id))
elif key not in fixed_keys:
attributes[key] = value
# attributes를 문자열로 변환
attributes_str = (
"\r\n\r\n".join([f"{key} : {value}" for key, value in attributes.items()])
if attributes
else ""
)
return cls(
store_name=form_data.get("store_info_name", ""),
store_id=form_data.get("store_id", ""),
attributes=attributes,
attributes_str=attributes_str,
lyrics_ids=lyrics_ids,
llm_model=form_data.get("llm_model", "gpt-4o"),
prompts=form_data.get("prompts", ""),
)
View File
Whitespace-only changes.
+24
View File
@@ -0,0 +1,24 @@
from uuid import UUID
from sqlalchemy.ext.asyncio import AsyncSession
from sqlmodel import SQLModel
class BaseService:
def __init__(self, model, session: AsyncSession):
self.model = model
self.session = session
async def _get(self, id: UUID):
return await self.session.get(self.model, id)
async def _add(self, entity):
self.session.add(entity)
await self.session.commit()
await self.session.refresh(entity)
return entity
async def _update(self, entity):
return await self._add(entity)
async def _delete(self, entity):
await self.session.delete(entity)
+852
View File
@@ -0,0 +1,852 @@
import random
from typing import List
from fastapi import Request, status
from fastapi.exceptions import HTTPException
from sqlalchemy import Connection, text
from sqlalchemy.exc import SQLAlchemyError
from app.lyrics.schemas.lyrics_schema import (
AttributeData,
PromptTemplateData,
SongFormData,
SongSampleData,
StoreData,
)
from app.utils.chatgpt_prompt import chatgpt_api
async def get_store_info(conn: Connection) -> List[StoreData]:
try:
query = """SELECT * FROM store_default_info;"""
result = await conn.execute(text(query))
all_store_info = [
StoreData(
id=row[0],
store_info=row[1],
store_name=row[2],
store_category=row[3],
store_region=row[4],
store_address=row[5],
store_phone_number=row[6],
created_at=row[7],
)
for row in result
]
result.close()
return all_store_info
except SQLAlchemyError as e:
print(e)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="요청하신 서비스가 잠시 내부적으로 문제가 발생하였습니다.",
)
except Exception as e:
print(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="알수없는 이유로 서비스 오류가 발생하였습니다",
)
async def get_attribute(conn: Connection) -> List[AttributeData]:
try:
query = """SELECT * FROM attribute;"""
result = await conn.execute(text(query))
all_attribute = [
AttributeData(
id=row[0],
attr_category=row[1],
attr_value=row[2],
created_at=row[3],
)
for row in result
]
result.close()
return all_attribute
except SQLAlchemyError as e:
print(e)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="요청하신 서비스가 잠시 내부적으로 문제가 발생하였습니다.",
)
except Exception as e:
print(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="알수없는 이유로 서비스 오류가 발생하였습니다",
)
async def get_attribute(conn: Connection) -> List[AttributeData]:
try:
query = """SELECT * FROM attribute;"""
result = await conn.execute(text(query))
all_attribute = [
AttributeData(
id=row[0],
attr_category=row[1],
attr_value=row[2],
created_at=row[3],
)
for row in result
]
result.close()
return all_attribute
except SQLAlchemyError as e:
print(e)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="요청하신 서비스가 잠시 내부적으로 문제가 발생하였습니다.",
)
except Exception as e:
print(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="알수없는 이유로 서비스 오류가 발생하였습니다",
)
async def get_sample_song(conn: Connection) -> List[SongSampleData]:
try:
query = """SELECT * FROM song_sample;"""
result = await conn.execute(text(query))
all_sample_song = [
SongSampleData(
id=row[0],
ai=row[1],
ai_model=row[2],
genre=row[3],
sample_song=row[4],
)
for row in result
]
result.close()
return all_sample_song
except SQLAlchemyError as e:
print(e)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="요청하신 서비스가 잠시 내부적으로 문제가 발생하였습니다.",
)
except Exception as e:
print(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="알수없는 이유로 서비스 오류가 발생하였습니다",
)
async def get_prompt_template(conn: Connection) -> List[PromptTemplateData]:
try:
query = """SELECT * FROM prompt_template;"""
result = await conn.execute(text(query))
all_prompt_template = [
PromptTemplateData(
id=row[0],
description=row[1],
prompt=row[2],
)
for row in result
]
result.close()
return all_prompt_template
except SQLAlchemyError as e:
print(e)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="요청하신 서비스가 잠시 내부적으로 문제가 발생하였습니다.",
)
except Exception as e:
print(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="알수없는 이유로 서비스 오류가 발생하였습니다",
)
async def get_song_result(conn: Connection) -> List[PromptTemplateData]:
try:
query = """SELECT * FROM prompt_template;"""
result = await conn.execute(text(query))
all_prompt_template = [
PromptTemplateData(
id=row[0],
description=row[1],
prompt=row[2],
)
for row in result
]
result.close()
return all_prompt_template
except SQLAlchemyError as e:
print(e)
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="요청하신 서비스가 잠시 내부적으로 문제가 발생하였습니다.",
)
except Exception as e:
print(e)
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="알수없는 이유로 서비스 오류가 발생하였습니다",
)
async def make_song_result(request: Request, conn: Connection):
try:
# 1. Form 데이터 파싱
form_data = await SongFormData.from_form(request)
print(f"\n{'=' * 60}")
print(f"Store ID: {form_data.store_id}")
print(f"Lyrics IDs: {form_data.lyrics_ids}")
print(f"Prompt IDs: {form_data.prompts}")
print(f"{'=' * 60}\n")
# 2. Store 정보 조회
store_query = """
SELECT * FROM store_default_info WHERE id=:id;
"""
store_result = await conn.execute(text(store_query), {"id": form_data.store_id})
all_store_info = [
StoreData(
id=row[0],
store_info=row[1],
store_name=row[2],
store_category=row[3],
store_region=row[4],
store_address=row[5],
store_phone_number=row[6],
created_at=row[7],
)
for row in store_result
]
if not all_store_info:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Store not found: {form_data.store_id}",
)
store_info = all_store_info[0]
print(f"Store: {store_info.store_name}")
# 3. 속성 조회 -- 단계별 선택 프로세서시 구현 필요 없음
# 4. Sample Song 조회 및 결합
combined_sample_song = None
if form_data.lyrics_ids:
print(f"\n[샘플 가사 조회] - {len(form_data.lyrics_ids)}개")
lyrics_query = """
SELECT sample_song FROM song_sample
WHERE id IN :ids
ORDER BY created_at;
"""
lyrics_result = await conn.execute(
text(lyrics_query), {"ids": tuple(form_data.lyrics_ids)}
)
sample_songs = [
row.sample_song for row in lyrics_result.fetchall() if row.sample_song
]
if sample_songs:
combined_sample_song = "\n\n".join(
[f"[샘플 {i + 1}]\n{song}" for i, song in enumerate(sample_songs)]
)
print(f"{len(sample_songs)}개의 샘플 가사 조회 완료")
else:
print("샘플 가사가 비어있습니다")
else:
print("선택된 lyrics가 없습니다")
# 5. 템플릿 가져오기
if not form_data.prompts:
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail="프롬프트 ID가 필요합니다",
)
print("템플릿 가져오기")
prompts_query = """
SELECT * FROM prompt_template WHERE id=:id;
"""
# ✅ 수정: store_query → prompts_query
prompts_result = await conn.execute(
text(prompts_query), {"id": form_data.prompts}
)
prompts_info = [
PromptTemplateData(
id=row[0],
description=row[1],
prompt=row[2],
)
for row in prompts_result
]
if not prompts_info:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Prompt not found: {form_data.prompts}",
)
prompt = prompts_info[0]
print(f"Prompt Template: {prompt.prompt}")
# ✅ 6. 프롬프트 조합
updated_prompt = prompt.prompt.replace("###", form_data.attributes_str).format(
name=store_info.store_name or "",
address=store_info.store_address or "",
category=store_info.store_category or "",
description=store_info.store_info or "",
)
updated_prompt += f"""
다음은 참고해야 하는 샘플 가사 정보입니다.
샘플 가사를 참고하여 작곡을 해주세요.
{combined_sample_song}
"""
print(f"\n[업데이트된 프롬프트]\n{updated_prompt}\n")
# 7. 모델에게 요청
generated_lyrics = await chatgpt_api.generate_lyrics(prompt=updated_prompt)
# 글자 수 계산
total_chars_with_space = len(generated_lyrics)
total_chars_without_space = len(
generated_lyrics.replace(" ", "")
.replace("\n", "")
.replace("\r", "")
.replace("\t", "")
)
# final_lyrics 생성
final_lyrics = f"""속성 {form_data.attributes_str}
전체 글자 수 (공백 포함): {total_chars_with_space}자
전체 글자 수 (공백 제외): {total_chars_without_space}자\r\n\r\n{generated_lyrics}"""
print("=" * 40)
print("[translate:form_data.attributes_str:] ", form_data.attributes_str)
print("[translate:total_chars_with_space:] ", total_chars_with_space)
print("[translate:total_chars_without_space:] ", total_chars_without_space)
print("[translate:final_lyrics:]")
print(final_lyrics)
print("=" * 40)
# 8. DB 저장
insert_query = """
INSERT INTO song_results_all (
store_info, store_name, store_category, store_address, store_phone_number,
description, prompt, attr_category, attr_value,
ai, ai_model, genre,
sample_song, result_song, created_at
) VALUES (
:store_info, :store_name, :store_category, :store_address, :store_phone_number,
:description, :prompt, :attr_category, :attr_value,
:ai, :ai_model, :genre,
:sample_song, :result_song, NOW()
);
"""
# ✅ attr_category, attr_value 추가
insert_params = {
"store_info": store_info.store_info or "",
"store_name": store_info.store_name,
"store_category": store_info.store_category or "",
"store_address": store_info.store_address or "",
"store_phone_number": store_info.store_phone_number or "",
"description": store_info.store_info or "",
"prompt": form_data.prompts,
"attr_category": ", ".join(form_data.attributes.keys())
if form_data.attributes
else "",
"attr_value": ", ".join(form_data.attributes.values())
if form_data.attributes
else "",
"ai": "ChatGPT",
"ai_model": form_data.llm_model,
"genre": "후크송",
"sample_song": combined_sample_song or "없음",
"result_song": final_lyrics,
}
await conn.execute(text(insert_query), insert_params)
await conn.commit()
print("결과 저장 완료")
print("\n전체 결과 조회 중...")
# 9. 생성 결과 가져오기 (created_at 역순)
select_query = """
SELECT * FROM song_results_all
ORDER BY created_at DESC;
"""
all_results = await conn.execute(text(select_query))
results_list = [
{
"id": row.id,
"store_info": row.store_info,
"store_name": row.store_name,
"store_category": row.store_category,
"store_address": row.store_address,
"store_phone_number": row.store_phone_number,
"description": row.description,
"prompt": row.prompt,
"attr_category": row.attr_category,
"attr_value": row.attr_value,
"ai": row.ai,
"ai_model": row.ai_model,
"genre": row.genre,
"sample_song": row.sample_song,
"result_song": row.result_song,
"created_at": row.created_at.isoformat() if row.created_at else None,
}
for row in all_results.fetchall()
]
print(f"전체 {len(results_list)}개의 결과 조회 완료\n")
return results_list
except HTTPException:
raise
except SQLAlchemyError as e:
print(f"Database Error: {e}")
import traceback
traceback.print_exc()
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="데이터베이스 연결에 문제가 발생했습니다.",
)
except Exception as e:
print(f"Unexpected Error: {e}")
import traceback
traceback.print_exc()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="서비스 처리 중 오류가 발생했습니다.",
)
async def get_song_result(conn: Connection): # 반환 타입 수정
try:
select_query = """
SELECT * FROM song_results_all
ORDER BY created_at DESC;
"""
all_results = await conn.execute(text(select_query))
results_list = [
{
"id": row.id,
"store_info": row.store_info,
"store_name": row.store_name,
"store_category": row.store_category,
"store_address": row.store_address,
"store_phone_number": row.store_phone_number,
"description": row.description,
"prompt": row.prompt,
"attr_category": row.attr_category,
"attr_value": row.attr_value,
"ai": row.ai,
"ai_model": row.ai_model,
"season": row.season,
"num_of_people": row.num_of_people,
"people_category": row.people_category,
"genre": row.genre,
"sample_song": row.sample_song,
"result_song": row.result_song,
"created_at": row.created_at.isoformat() if row.created_at else None,
}
for row in all_results.fetchall()
]
print(f"전체 {len(results_list)}개의 결과 조회 완료\n")
return results_list
except HTTPException: # HTTPException은 그대로 raise
raise
except SQLAlchemyError as e:
print(f"Database Error: {e}")
import traceback
traceback.print_exc()
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="데이터베이스 연결에 문제가 발생했습니다.",
)
except Exception as e:
print(f"Unexpected Error: {e}")
import traceback
traceback.print_exc()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="서비스 처리 중 오류가 발생했습니다.",
)
async def make_automation(request: Request, conn: Connection):
try:
# 1. Form 데이터 파싱
form_data = await SongFormData.from_form(request)
print(f"\n{'=' * 60}")
print(f"Store ID: {form_data.store_id}")
print(f"{'=' * 60}\n")
# 2. Store 정보 조회
store_query = """
SELECT * FROM store_default_info WHERE id=:id;
"""
store_result = await conn.execute(text(store_query), {"id": form_data.store_id})
all_store_info = [
StoreData(
id=row[0],
store_info=row[1],
store_name=row[2],
store_category=row[3],
store_region=row[4],
store_address=row[5],
store_phone_number=row[6],
created_at=row[7],
)
for row in store_result
]
if not all_store_info:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail=f"Store not found: {form_data.store_id}",
)
store_info = all_store_info[0]
print(f"Store: {store_info.store_name}")
# 3. 속성 조회 -- 단계별 선택 프로세서시 구현 필요 없음
attribute_query = """
SELECT * FROM attribute;
"""
attribute_results = await conn.execute(text(attribute_query))
# 결과 가져오기
attribute_rows = attribute_results.fetchall()
formatted_attributes = ""
selected_categories = []
selected_values = []
if attribute_rows:
attribute_list = [
AttributeData(
id=row[0],
attr_category=row[1],
attr_value=row[2],
created_at=row[3],
)
for row in attribute_rows
]
# ✅ 각 category에서 하나의 value만 랜덤 선택
formatted_pairs = []
for attr in attribute_list:
# 쉼표로 분리 및 공백 제거
values = [v.strip() for v in attr.attr_value.split(",") if v.strip()]
if values:
# 랜덤하게 하나만 선택
selected_value = random.choice(values)
formatted_pairs.append(f"{attr.attr_category} : {selected_value}")
# ✅ 선택된 category와 value 저장
selected_categories.append(attr.attr_category)
selected_values.append(selected_value)
# 최종 문자열 생성
formatted_attributes = "\n".join(formatted_pairs)
print(f"\n[포맷팅된 문자열 속성 정보]\n{formatted_attributes}\n")
else:
print("속성 데이터가 없습니다")
formatted_attributes = ""
# 4. 템플릿 가져오기
print("템플릿 가져오기 (ID=1)")
prompts_query = """
SELECT * FROM prompt_template WHERE id=1;
"""
prompts_result = await conn.execute(text(prompts_query))
row = prompts_result.fetchone()
if not row:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="Prompt ID 1 not found",
)
prompt = PromptTemplateData(
id=row[0],
description=row[1],
prompt=row[2],
)
print(f"Prompt Template: {prompt.prompt}")
# 5. 템플릿 조합
updated_prompt = prompt.prompt.replace("###", formatted_attributes).format(
name=store_info.store_name or "",
address=store_info.store_address or "",
category=store_info.store_category or "",
description=store_info.store_info or "",
)
print("\n" + "=" * 80)
print("업데이트된 프롬프트")
print("=" * 80)
print(updated_prompt)
print("=" * 80 + "\n")
# 4. Sample Song 조회 및 결합
combined_sample_song = None
if form_data.lyrics_ids:
print(f"\n[샘플 가사 조회] - {len(form_data.lyrics_ids)}개")
lyrics_query = """
SELECT sample_song FROM song_sample
WHERE id IN :ids
ORDER BY created_at;
"""
lyrics_result = await conn.execute(
text(lyrics_query), {"ids": tuple(form_data.lyrics_ids)}
)
sample_songs = [
row.sample_song for row in lyrics_result.fetchall() if row.sample_song
]
if sample_songs:
combined_sample_song = "\n\n".join(
[f"[샘플 {i + 1}]\n{song}" for i, song in enumerate(sample_songs)]
)
print(f"{len(sample_songs)}개의 샘플 가사 조회 완료")
else:
print("샘플 가사가 비어있습니다")
else:
print("선택된 lyrics가 없습니다")
# 1. song_sample 테이블의 모든 ID 조회
print("\n[샘플 가사 랜덤 선택]")
all_ids_query = """
SELECT id FROM song_sample;
"""
ids_result = await conn.execute(text(all_ids_query))
all_ids = [row.id for row in ids_result.fetchall()]
print(f"전체 샘플 가사 개수: {len(all_ids)}개")
# 2. 랜덤하게 3개 선택 (또는 전체 개수가 3개 미만이면 전체)
combined_sample_song = None
if all_ids:
# 3개 또는 전체 개수 중 작은 값 선택
sample_count = min(3, len(all_ids))
selected_ids = random.sample(all_ids, sample_count)
print(f"랜덤 선택된 ID: {selected_ids}")
# 3. 선택된 ID로 샘플 가사 조회
lyrics_query = """
SELECT sample_song FROM song_sample
WHERE id IN :ids
ORDER BY created_at;
"""
lyrics_result = await conn.execute(
text(lyrics_query), {"ids": tuple(selected_ids)}
)
sample_songs = [
row.sample_song for row in lyrics_result.fetchall() if row.sample_song
]
# 4. combined_sample_song 생성
if sample_songs:
combined_sample_song = "\n\n".join(
[f"[샘플 {i + 1}]\n{song}" for i, song in enumerate(sample_songs)]
)
print(f"{len(sample_songs)}개의 샘플 가사 조회 완료")
else:
print("샘플 가사가 비어있습니다")
else:
print("song_sample 테이블에 데이터가 없습니다")
# 5. 프롬프트에 샘플 가사 추가
if combined_sample_song:
updated_prompt += f"""
다음은 참고해야 하는 샘플 가사 정보입니다.
샘플 가사를 참고하여 작곡을 해주세요.
{combined_sample_song}
"""
print("샘플 가사 정보가 프롬프트에 추가되었습니다")
else:
print("샘플 가사가 없어 기본 프롬프트만 사용합니다")
print(f"\n[최종 프롬프트 길이: {len(updated_prompt)} 자]\n")
# 7. 모델에게 요청
generated_lyrics = await chatgpt_api.generate_lyrics(prompt=updated_prompt)
# 글자 수 계산
total_chars_with_space = len(generated_lyrics)
total_chars_without_space = len(
generated_lyrics.replace(" ", "")
.replace("\n", "")
.replace("\r", "")
.replace("\t", "")
)
# final_lyrics 생성
final_lyrics = f"""속성 {formatted_attributes}
전체 글자 수 (공백 포함): {total_chars_with_space}자
전체 글자 수 (공백 제외): {total_chars_without_space}자\r\n\r\n{generated_lyrics}"""
# 8. DB 저장
insert_query = """
INSERT INTO song_results_all (
store_info, store_name, store_category, store_address, store_phone_number,
description, prompt, attr_category, attr_value,
ai, ai_model, genre,
sample_song, result_song, created_at
) VALUES (
:store_info, :store_name, :store_category, :store_address, :store_phone_number,
:description, :prompt, :attr_category, :attr_value,
:ai, :ai_model, :genre,
:sample_song, :result_song, NOW()
);
"""
print("\n[insert_params 선택된 속성 확인]")
print(f"Categories: {selected_categories}")
print(f"Values: {selected_values}")
print()
# attr_category, attr_value
insert_params = {
"store_info": store_info.store_info or "",
"store_name": store_info.store_name,
"store_category": store_info.store_category or "",
"store_address": store_info.store_address or "",
"store_phone_number": store_info.store_phone_number or "",
"description": store_info.store_info or "",
"prompt": prompt.id,
# 랜덤 선택된 category와 value 사용
"attr_category": ", ".join(selected_categories)
if selected_categories
else "",
"attr_value": ", ".join(selected_values) if selected_values else "",
"ai": "ChatGPT",
"ai_model": "gpt-4o",
"genre": "후크송",
"sample_song": combined_sample_song or "없음",
"result_song": final_lyrics,
}
await conn.execute(text(insert_query), insert_params)
await conn.commit()
print("결과 저장 완료")
print("\n전체 결과 조회 중...")
# 9. 생성 결과 가져오기 (created_at 역순)
select_query = """
SELECT * FROM song_results_all
ORDER BY created_at DESC;
"""
all_results = await conn.execute(text(select_query))
results_list = [
{
"id": row.id,
"store_info": row.store_info,
"store_name": row.store_name,
"store_category": row.store_category,
"store_address": row.store_address,
"store_phone_number": row.store_phone_number,
"description": row.description,
"prompt": row.prompt,
"attr_category": row.attr_category,
"attr_value": row.attr_value,
"ai": row.ai,
"ai_model": row.ai_model,
"genre": row.genre,
"sample_song": row.sample_song,
"result_song": row.result_song,
"created_at": row.created_at.isoformat() if row.created_at else None,
}
for row in all_results.fetchall()
]
print(f"전체 {len(results_list)}개의 결과 조회 완료\n")
return results_list
except HTTPException:
raise
except SQLAlchemyError as e:
print(f"Database Error: {e}")
import traceback
traceback.print_exc()
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="데이터베이스 연결에 문제가 발생했습니다.",
)
except Exception as e:
print(f"Unexpected Error: {e}")
import traceback
traceback.print_exc()
raise HTTPException(
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
detail="서비스 처리 중 오류가 발생했습니다.",
)
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
View File
Whitespace-only changes.
Whitespace-only changes.
View File
Whitespace-only changes.