Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
130 changes: 130 additions & 0 deletions Back/Back_project/haru/tests.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,133 @@
from django.test import TestCase
from datetime import datetime
from haru.models import DIARY,DIARY_DETAIL
from webpage.models import User
from calendar import monthrange
import pytz
from random import choice

# Create your tests here.

def create_sample_diary(user_id, year, month):
user = User.objects.get(id=user_id)
emotions = ["기쁨", "슬픔", "분노", "무감정"]
start_date = datetime(year, month, 1)
_, end_day = monthrange(year, month)
end_date = datetime(year, month, end_day)
start_day = start_date.day

for i in range(start_day, end_day+1):
try:
diary = DIARY(
USER_ID=user,
DATE=datetime(year, month, i),
EMO=choice(emotions),
ORI_FILE_DIR="Test Original Path"
)
diary.save()

detail = DIARY_DETAIL(
ID=diary.id,
SHORT_TEXT="Test Short Text",
FEEDBACK_TEXT="Test FeedBack Test",
FEEDBACK_FILE_DIR="Test Feedback Path"
)

detail.save()

except Exception as e:
print(str(e))
return


def get_date_emotion_pairs(user_id, year, month):
user = User.objects.get(id=user_id)
start_date = datetime(year, month, 1)
_, end_day = monthrange(year, month)
end_date = datetime(year, month, end_day)
start_day = start_date.day

diary_query = DIARY.objects.filter(DATE__year=str(year),
DATE__month=str(month),
USER_ID=user)

pairs = []

for i in range(start_day, end_day+1):
diary = diary_query.filter(DATE__day=str(i))
if diary.count() != 1:
continue

diary = diary.first()

pairs.append({
"day": i,
"emo": diary.EMO
})

print(pairs)


#test with 161
def test_voice_synth(diary_id):
import requests
from Back_project.settings import FLASK_IP

json_data = {
'gender' : 1,
'age_group': 2,
'speech_style': 2,
'emotion': "기쁨",
'diary_id': diary_id,
'time_tag': "aaa_20240603132928",
'ori_file_dir' : "ORI_FILE/ori_aaa_20240603132928.wav",
'client_ip' : "http://175.125.148.178:2871"
}

print(requests.post(f"http://{FLASK_IP}:9000/upload", data = json_data))


def test_timezone():
from django.utils import timezone
from haru.models import DIARY
from webpage.models import User

KST = pytz.timezone('Asia/Seoul')
UTC = pytz.timezone('UTC')
now_utc = timezone.now().replace(tzinfo=UTC)
now_kst = now_utc.astimezone(KST)
date = now_kst

new_diary = DIARY(
USER_ID=User.objects.get(id=2),
DATE=date,
EMO="Timezone Test",
ORI_FILE_DIR="TimezoneTest"
)

new_diary.save()



def test_get_voice():
from Back_project import settings
import boto3

key = "ORI_FILE/ori_aaa_20240605133135.wav"
try:
bucket_name = settings.AWS_STORAGE_BUCKET_NAME
s3 = boto3.client(
's3',
aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
region_name=settings.AWS_S3_REGION_NAME
)
voice_file = s3.get_object(Bucket=bucket_name, Key=key)
voice_data = voice_file['Body'].read()

with open("/mnt/d/test.wav", 'wb') as wav:
wav.write(voice_data)

except Exception as e:
print(str(e))

4 changes: 2 additions & 2 deletions Back/Back_project/haru/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
app_name = 'haru'
urlpatterns =[
path('post/', post.record, name='post'),
path('calendar/', get.get_calendar,name='get_calendar'),
path('get/', get.get_date, name='get'),
path('calendar/<int:year>/<int:month>/', get.get_calendar,name='get_calendar'),
path('get/<int:year>/<int:month>/<int:day>/', get.get_date, name='get'),
path('build/',post.build_diary, name='build'),
path('voice/<int:year>/<int:month>/<int:day>/<str:type>/', get.get_voice_file, name="get_voice_file")
]
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
122 changes: 75 additions & 47 deletions Back/Back_project/haru/views/get.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import os
from django.shortcuts import render,redirect
from django.contrib import messages
from django.contrib.auth.models import User
from webpage.models import User
from haru.models import DIARY,DIARY_DETAIL
from datetime import datetime, timedelta
from calendar import monthrange
Expand All @@ -13,59 +13,71 @@
from django.conf import settings
from time import timezone

def get_diary_entries_for_month(year, month):
today = timezone.now().date()
def get_diary_entries_for_month(user_id, year, month):
user = User.objects.get(id=user_id)
start_date = datetime(year, month, 1)
_, last_day = monthrange(year, month)
end_date = datetime(year, month, last_day)
_, end_day = monthrange(year, month)
end_date = datetime(year, month, end_day)
start_day = start_date.day

# 범위에 해당하는 데이터 조회
diary_entries = DIARY.objects.filter(
date__range=(start_date, end_date),
date__lte = today
)
diary_query = DIARY.objects.filter(DATE__year=str(year),
DATE__month=str(month),
USER_ID=user)

emo_list = [entry.emo for entry in diary_entries]
pairs = []

for i in range(start_day, end_day+1):
diary = diary_query.filter(DATE__day=str(i))
if diary.count() != 1:
continue

days_in_month = last_day
emo_list += [None] * (days_in_month - len(emo_list))
diary = diary.first()

return {'emo_list':emo_list,'last_day':last_day}
pairs.append({
"day": i,
"emo": diary.EMO
})

def get_calendar(request):
return pairs


def get_calendar(request, year, month):
if request.user.is_authenticated:
user_id = request.user.id
else:
messages.warning(request, "로그인이 필요한 서비스입니다.")
return redirect('webpage:index')
if request.method == "POST":
selected_date = request.POST.get('selected_date')
context = get_diary_entries_for_month(selected_date['year'],selected_date['month'])
return render(request, 'calendar.html', context['emo_list'],context['last_day'])
return HttpResponse("Login First", status=403)
pairs = get_diary_entries_for_month(user_id, year, month)
return JsonResponse({'pairs' : pairs})

def get_date(request):
def get_date(request, year, month, day):
if request.user.is_authenticated:
user_id = request.user.id
else:
messages.warning(request, "로그인이 필요한 서비스입니다.")
return render('webpage:index')
if request.method == "GET":
date = request.GET.get('date')
year = date['year']
month = date['month']
day = date['month']

diary, detail, response = get_diary(request,user_id,date)
date = datetime(year,month,day)

if diary == None and detail == None:
return response
diary, detail, response = get_diary(request,user_id,date)

res = {
"emo": diary.EMO,
'feedback_text': detail.FEEDBACK_TEXT,
'original': f"haru/voice/{date.year}/{date.month}/{date.day}/original/",
'feedback': f"haru/voice/{date.year}/{date.month}/{date.day}/feedback/"
}
if diary == None and detail == None: #for test
res = {
"emo": "테스트 감정",
'short_text': "Test short text",
'feedback_text': "테스트 피드백 텍스트",
'original': f"haru/voice/{date.year}/{date.month}/{date.day}/original/",
'feedback': f"haru/voice/{date.year}/{date.month}/{date.day}/feedback/"
}

else:
res = {
"emo": diary.EMO,
'short_text': detail.SHORT_TEXT,
'feedback_text': detail.FEEDBACK_TEXT,
'original': f"haru/voice/{date.year}/{date.month}/{date.day}/original/",
'feedback': f"haru/voice/{date.year}/{date.month}/{date.day}/feedback/"
}


return JsonResponse(res)
Expand All @@ -75,15 +87,18 @@ def get_date(request):


def get_diary(request, user_id, date):
diary_query = DIARY.objects.filter(USER_ID=user_id, DATE=date)
if diary_query.count() != 1:
user = User.objects.get(id=user_id)
print(date)
diary_query = DIARY.objects.filter(USER_ID=user, DATE__year=date.year, DATE__month=date.month, DATE__day=date.day)
if diary_query.count() == 0:
return None, None, HttpResponse(f"Diary on {date} not found", status=404)

diary = diary_query.first()

detail_query = DIARY_DETAIL.objects.filter(ID=diary.id)

if detail_query.count() != 1:
print(f"Internal Error: found {detail_query.count()} DIARY_DETAIL for DIARY({date})")
return None, None, HttpResponse(f"Internal Error: found {detail_query.count()} DIARY_DETAIL for DIARY({date})", status=500)

detail = detail_query.first()
Expand All @@ -95,18 +110,24 @@ def get_voice_file(request, year, month, day, type):
if request.user.is_authenticated == False:
return HttpResponse("Login Required", status=403)

bucket_name = settings.AWS_STORAGE_BUCKET_NAME
s3 = boto3.client('s3')

date = {}

date['year'] = year
date['month'] = month
date['month'] = day
date = datetime(year, month, day)

diary, detail, response = get_diary(request, request.user.id, date)

if diary == None and detail == None:
print(diary)
print(detail)
print(response)

if diary == None or detail == None or diary.ORI_FILE_DIR == "Test Original Path" or detail.FEEDBACK_FILE_DIR == "Test Feedback Path":#for test
from Back_project.settings import MEDIA_ROOT
if type == "original" or type == "feedback":
with open(f"{MEDIA_ROOT}/{type}.wav", "rb") as sample:
response = HttpResponse(sample.read(), content_type="audio/wav")

else:
response = HttpResponse(f"Diary not found + invalid type({type})", status="404")

return response

key = ""
Expand All @@ -118,11 +139,18 @@ def get_voice_file(request, year, month, day, type):
key = detail.FEEDBACK_FILE_DIR

try:
bucket_name = settings.AWS_STORAGE_BUCKET_NAME
s3 = boto3.client(
's3',
aws_access_key_id=settings.AWS_ACCESS_KEY_ID,
aws_secret_access_key=settings.AWS_SECRET_ACCESS_KEY,
region_name=settings.AWS_S3_REGION_NAME
)
voice_file = s3.get_object(Bucket=bucket_name, Key=key)
voice_data = voice_file.read()
voice_data = voice_file['Body'].read()

return HttpResponse(voice_data, content_type="audio/wav")

except Exception as e:
print(str(e))
return HttpResponse("Error retrieving file from S3: " + str(e), status=500)

Loading