diff --git a/Back/Back_project/haru/__pycache__/__init__.cpython-310.pyc b/Back/Back_project/haru/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..51e0b7b Binary files /dev/null and b/Back/Back_project/haru/__pycache__/__init__.cpython-310.pyc differ diff --git a/Back/Back_project/haru/__pycache__/admin.cpython-310.pyc b/Back/Back_project/haru/__pycache__/admin.cpython-310.pyc new file mode 100644 index 0000000..c4454ab Binary files /dev/null and b/Back/Back_project/haru/__pycache__/admin.cpython-310.pyc differ diff --git a/Back/Back_project/haru/__pycache__/apps.cpython-310.pyc b/Back/Back_project/haru/__pycache__/apps.cpython-310.pyc new file mode 100644 index 0000000..2f2ca18 Binary files /dev/null and b/Back/Back_project/haru/__pycache__/apps.cpython-310.pyc differ diff --git a/Back/Back_project/haru/__pycache__/models.cpython-310.pyc b/Back/Back_project/haru/__pycache__/models.cpython-310.pyc new file mode 100644 index 0000000..b706463 Binary files /dev/null and b/Back/Back_project/haru/__pycache__/models.cpython-310.pyc differ diff --git a/Back/Back_project/haru/__pycache__/tests.cpython-310.pyc b/Back/Back_project/haru/__pycache__/tests.cpython-310.pyc new file mode 100644 index 0000000..ab4187b Binary files /dev/null and b/Back/Back_project/haru/__pycache__/tests.cpython-310.pyc differ diff --git a/Back/Back_project/haru/__pycache__/urls.cpython-310.pyc b/Back/Back_project/haru/__pycache__/urls.cpython-310.pyc new file mode 100644 index 0000000..bc1b712 Binary files /dev/null and b/Back/Back_project/haru/__pycache__/urls.cpython-310.pyc differ diff --git a/Back/Back_project/haru/migrations/__pycache__/0001_initial.cpython-310.pyc b/Back/Back_project/haru/migrations/__pycache__/0001_initial.cpython-310.pyc new file mode 100644 index 0000000..e8f7d71 Binary files /dev/null and b/Back/Back_project/haru/migrations/__pycache__/0001_initial.cpython-310.pyc differ diff --git a/Back/Back_project/haru/migrations/__pycache__/__init__.cpython-310.pyc b/Back/Back_project/haru/migrations/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..e6e70cd Binary files /dev/null and b/Back/Back_project/haru/migrations/__pycache__/__init__.cpython-310.pyc differ diff --git a/Back/Back_project/haru/tests.py b/Back/Back_project/haru/tests.py index 7ce503c..8f4f608 100644 --- a/Back/Back_project/haru/tests.py +++ b/Back/Back_project/haru/tests.py @@ -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)) + diff --git a/Back/Back_project/haru/urls.py b/Back/Back_project/haru/urls.py index 039a150..a2302e5 100644 --- a/Back/Back_project/haru/urls.py +++ b/Back/Back_project/haru/urls.py @@ -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///', get.get_calendar,name='get_calendar'), + path('get////', get.get_date, name='get'), path('build/',post.build_diary, name='build'), path('voice/////', get.get_voice_file, name="get_voice_file") ] \ No newline at end of file diff --git a/Back/Back_project/haru/views/__pycache__/__init__.cpython-310.pyc b/Back/Back_project/haru/views/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000..2cc0fc5 Binary files /dev/null and b/Back/Back_project/haru/views/__pycache__/__init__.cpython-310.pyc differ diff --git a/Back/Back_project/haru/views/__pycache__/get.cpython-310.pyc b/Back/Back_project/haru/views/__pycache__/get.cpython-310.pyc new file mode 100644 index 0000000..a7ca325 Binary files /dev/null and b/Back/Back_project/haru/views/__pycache__/get.cpython-310.pyc differ diff --git a/Back/Back_project/haru/views/__pycache__/post.cpython-310.pyc b/Back/Back_project/haru/views/__pycache__/post.cpython-310.pyc new file mode 100644 index 0000000..efb9bab Binary files /dev/null and b/Back/Back_project/haru/views/__pycache__/post.cpython-310.pyc differ diff --git a/Back/Back_project/haru/views/__pycache__/upload_file_to_s3.cpython-310.pyc b/Back/Back_project/haru/views/__pycache__/upload_file_to_s3.cpython-310.pyc new file mode 100644 index 0000000..6c893b9 Binary files /dev/null and b/Back/Back_project/haru/views/__pycache__/upload_file_to_s3.cpython-310.pyc differ diff --git a/Back/Back_project/haru/views/get.py b/Back/Back_project/haru/views/get.py index b4fdc4e..166e0a4 100644 --- a/Back/Back_project/haru/views/get.py +++ b/Back/Back_project/haru/views/get.py @@ -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 @@ -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) @@ -75,8 +87,10 @@ 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() @@ -84,6 +98,7 @@ def get_diary(request, user_id, date): 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() @@ -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 = "" @@ -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) - diff --git a/Back/Back_project/haru/views/post.py b/Back/Back_project/haru/views/post.py index f59f3fe..471602b 100644 --- a/Back/Back_project/haru/views/post.py +++ b/Back/Back_project/haru/views/post.py @@ -1,5 +1,6 @@ from django.shortcuts import render, redirect from haru.views.upload_file_to_s3 import upload_wav_to_s3 +from webpage.models import User from haru.models import DIARY,DIARY_DETAIL,Haru_setting from django.http import HttpResponse, HttpResponseBadRequest,JsonResponse from django.utils import timezone @@ -7,35 +8,44 @@ import json import pytz import requests +from datetime import datetime +from django.conf import settings +import socket + +def set_tag(date,user_id): + + year = date.year + month = "{:02}".format(date.month) + day = "{:02}".format(date.day) + hour = "{:02}".format(date.hour) + minute = "{:02}".format(date.minute) + second = "{:02}".format(date.second) + time_tag = f"{user_id}_{year}{month}{day}{hour}{minute}{second}" + return time_tag + @csrf_exempt def record(request): if not request.user.is_authenticated: return HttpResponseBadRequest("로그인 오류") - - user_id = request.user.id - + + user_id = User.objects.get(id=request.user.id) if request.method == "POST": 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 + emo = request.POST.get('EMO') wav_file = request.FILES.get('wav_file') - date = now_kst - year = date.year - month = "{:02}".format(date.month) - day = "{:02}".format(date.day) - hour = "{:02}".format(date.hour) - minute = "{:02}".format(date.minute) - second = "{:02}".format(date.second) - time_tag = f"{user_id}_{year}{month}{day}{hour}{minute}{second}" + time_tag = set_tag(date,user_id) path_tag = f"ori_{time_tag}.wav" + print(emo, wav_file) if not emo or not wav_file: return HttpResponseBadRequest("필수 필드가 누락되었습니다.") try: - response = upload_wav_to_s3(request,"ORI_FILE",path_tag) if response.status_code == 200: response_data = json.loads(response.content) @@ -46,32 +56,54 @@ def record(request): return HttpResponseBadRequest(f"파일 업로드 예외 발생: {e}") + new_diary = DIARY( - USER_ID_id=user_id, + USER_ID=user_id, DATE=date, EMO=emo, ORI_FILE_DIR=ori_file_path ) new_diary.save() id = new_diary.id - haru_info = Haru_setting.objects.filter(ID=user_id) - flask_server_url = 'http://127.0.0.1:5001/receive' - files = { - 'file': (wav_file.name, wav_file.read(), 'audio/wav') - } - json_data = { - 'data': json.dumps({ + + haru_info = Haru_setting.objects.filter(USER_ID=request.user.id) + + json_data = {} + + if haru_info.count() != 1: + print(f"Cannot find HARU_SETTING for user id({user_id})") + json_data = { + 'gender' : 1, + 'age_group': 2, + 'speech_style': 2, + 'emotion': emo, + 'diary_id': id, + 'time_tag': time_tag, + 'ori_file_dir' : ori_file_path, + 'client_ip' : "http://175.125.148.178:2871" + } + + else: + haru_info = haru_info.first() + json_data = { 'gender' : haru_info.HARU_GENDER, - 'age_group' : haru_info.HARU_OLD, - 'speech_style' : haru_info.HARU_STYLE, - 'emotion' : emo, - 'diary_id' : id, - 'user_id' : user_id, - 'time_tag' : time_tag - }) - } - new_response = requests.post(flask_server_url,file = files,data = json_data) - send_request_flask(new_response) + 'age_group': haru_info.HARU_OLD, + 'speech_style': haru_info.HARU_STYLE, + 'emotion': emo, + 'diary_id': id, + 'time_tag': time_tag, + 'ori_file_dir' : ori_file_path, + 'client_ip' : "http://175.125.148.178:2871" + } + + + + flask_server_url = f'http://{settings.FLASK_IP}:9000/upload' + + print(json_data) + new_response = requests.post(flask_server_url, data = json_data) + print(new_response) + #send_request_flask(new_response) return HttpResponse("일기 작성 완료.") else: return HttpResponseBadRequest("잘못된 요청 방법") @@ -82,12 +114,12 @@ def send_request_flask(response): return JsonResponse(response.json(), status=response.status_code) - +@csrf_exempt def build_diary(request): if request.method == "POST": feedback_text = request.POST.get('feedback_text') short_text = request.POST.get('short_text') - feedback_file = request.FILES.get('feedback_file') + feedback_file = request.FILES.get('wav_file') id = request.POST.get('id') time_tag = request.POST.get('time_tag') path_tag = f"feedback_{time_tag}.wav" @@ -105,5 +137,4 @@ def build_diary(request): FEEDBACK_FILE_DIR=feedback_file_path ) new_detail.save() - return HttpResponse("일기 상세 작성 완료.") - + return HttpResponse("일기 상세 작성 완료.") \ No newline at end of file diff --git a/Back/Back_project/haru/views/upload_file_to_s3.py b/Back/Back_project/haru/views/upload_file_to_s3.py index b055d67..d89f007 100644 --- a/Back/Back_project/haru/views/upload_file_to_s3.py +++ b/Back/Back_project/haru/views/upload_file_to_s3.py @@ -23,9 +23,6 @@ def upload_wav_to_s3(request,content,path_tag): s3_client.upload_fileobj(wav_file, bucket_name, file_path) - # 업로드된 파일의 URL 생성 - s3_file_url = f"https://{bucket_name}.s3.amazonaws.com/{file_path}" - - return JsonResponse({'url': s3_file_url}) + return JsonResponse({'url': file_path}) else: return JsonResponse({'error': 'No WAV file uploaded'}, status=400) \ No newline at end of file diff --git a/Back/Back_project/media/feedback.wav b/Back/Back_project/media/feedback.wav new file mode 100755 index 0000000..586ea31 Binary files /dev/null and b/Back/Back_project/media/feedback.wav differ diff --git a/Back/Back_project/media/original.wav b/Back/Back_project/media/original.wav new file mode 100755 index 0000000..d2fc589 Binary files /dev/null and b/Back/Back_project/media/original.wav differ