Skip to content

Commit

Permalink
Merge pull request #43 from TUK-DP/develop
Browse files Browse the repository at this point in the history
deploy 0.3
  • Loading branch information
Leewonchan14 authored Mar 7, 2024
2 parents b0ad039 + f30e5a6 commit bacba26
Show file tree
Hide file tree
Showing 7 changed files with 305 additions and 165 deletions.
13 changes: 13 additions & 0 deletions config/basemodel.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
from django.db import models
from django.http import JsonResponse
from rest_framework import status


class BaseModel(models.Model):
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)

# deleted_at = models.DateTimeField(blank=True, null=True)

class Meta:
abstract = True


class ApiResponse:
@staticmethod
def on_success(result, response_status=status.HTTP_200_OK):
return JsonResponse({'isSuccess': True, 'result': result}, status=response_status)

@staticmethod
def on_fail(message, response_status=status.HTTP_400_BAD_REQUEST):
return JsonResponse({'isSuccess': False, 'message': message}, status=response_status)
43 changes: 43 additions & 0 deletions diary/migrations/0004_keywords_questions_delete_quizs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
# Generated by Django 5.0.2 on 2024-03-06 08:50

import django.db.models.deletion
from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('diary', '0003_remove_diary_content_alter_sentences_diary_quizs_and_more'),
]

operations = [
migrations.CreateModel(
name='Keywords',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('keyword', models.CharField(max_length=100)),
('sentence', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='keywords', to='diary.sentences')),
],
options={
'abstract': False,
},
),
migrations.CreateModel(
name='Questions',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created_at', models.DateTimeField(auto_now_add=True)),
('updated_at', models.DateTimeField(auto_now=True)),
('question', models.TextField()),
('keyword', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='questions', to='diary.keywords')),
],
options={
'abstract': False,
},
),
migrations.DeleteModel(
name='Quizs',
),
]
10 changes: 7 additions & 3 deletions diary/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,8 +20,12 @@ class Sentences(BaseModel):

diary = models.ForeignKey('diary.Diary', related_name='sentences', on_delete=models.CASCADE)

class Quizs(BaseModel):
class Keywords(BaseModel):
keyword = models.CharField(max_length=100)

sentence = models.ForeignKey('diary.Sentences', related_name='keywords', on_delete=models.CASCADE)

class Questions(BaseModel):
question = models.TextField()
answer = models.CharField(max_length=50)

sentence = models.ForeignKey('diary.Sentences', related_name='quizs', on_delete=models.CASCADE)
keyword = models.ForeignKey('diary.Keywords', related_name='questions', on_delete=models.CASCADE)
120 changes: 84 additions & 36 deletions diary/serializers.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from rest_framework import serializers
from rest_framework import serializers, status

from users.models import User
from users.serializers import UserSafeSerializer
from .models import Diary, Sentences, Quizs
from .models import Diary, Sentences, Keywords, Questions


class DiarySerializer(serializers.ModelSerializer):
Expand All @@ -12,34 +12,47 @@ class Meta:
model = Diary
fields = '__all__'


class DiarySimpleSerializer(serializers.ModelSerializer):
user = UserSafeSerializer(read_only=True)

class Meta:
model = Diary
fields = ['id', 'user', 'title']


class SentenceSerializer(serializers.ModelSerializer):
diay = DiarySerializer(read_only=True)

class Meta:
model = Sentences
fields = '__all__'


class SentenceSimpleSerializer(serializers.ModelSerializer):
diary = DiarySimpleSerializer(read_only=True)

class Meta:
model = Sentences
fields = ['id', 'diary', 'sentence']

class QuizSerializer(serializers.ModelSerializer):
sentences = SentenceSerializer(read_only=True)

class KeywordSerializer(serializers.ModelSerializer):
sentence = SentenceSerializer(read_only=True)

class Meta:
model = Keywords
fields = '__all__'


class QuestionSerializer(serializers.ModelSerializer):
keyword = KeywordSerializer(read_only=True)

class Meta:
model = Quizs
model = Questions
fields = '__all__'


class DiaryCreateRequest(serializers.ModelSerializer):
userId = serializers.IntegerField()

Expand All @@ -53,56 +66,91 @@ def to_diary(self, user: User) -> DiarySerializer:
newDiary.save(user=user)
return newDiary


class WriteRequest(serializers.Serializer):
userId = serializers.IntegerField()
title = serializers.CharField(max_length=100)
content = serializers.CharField()

class Meta:
model = Diary
fields = '__all__'
def is_valid(self, raise_exception=False):
super_valid = super().is_valid()
# 유효하지 않다면 False, 400 반환
if not super_valid:
return False, status.HTTP_400_BAD_REQUEST

def create(self, validated_data):
user_id = validated_data.pop('userId')
try:
user = User.objects.get(pk=user_id)
except User.DoesNotExist:
raise serializers.ValidationError("유저가 존재하지 않습니다.")

validated_data['user'] = user
content_data = validated_data.pop('content')
diary = Diary.objects.create(**validated_data)
Sentences.objects.create(diary=diary, sentence=content_data)
# 유효하다면 userId가 존재하는지 확인
is_user_exist = User.objects.filter(id=self.data['userId']).exists()

# 존재하지 않는다면 False, 404 반환
if not is_user_exist:
self._errors['userId'] = [f'userId: {self.data.get("userId")} 가 존재하지 않습니다.']
return False, status.HTTP_404_NOT_FOUND

return True, status.HTTP_200_OK

return diary

class UpdateRequest(serializers.Serializer):
diaryId = serializers.IntegerField()
userId = serializers.IntegerField()
title = serializers.CharField(max_length=100)
content = serializers.CharField()

class Meta:
model = Diary
fields = '__all__'
def is_valid(self, raise_exception=False):
super_valid = super().is_valid()
# 유효하지 않다면 False, 400 반환
if not super_valid:
return False, status.HTTP_400_BAD_REQUEST

# userId가 존재하는지 확인
is_user_exist = User.objects.filter(id=self.data['userId']).exists()
# 존재하지 않는다면 False, 404 반환
if not is_user_exist:
self._errors['userId'] = [f'userId: {self.data.get("userId")} 가 존재하지 않습니다.']
return False, status.HTTP_404_NOT_FOUND

def create(self, validated_data):
diary_id = validated_data.pop('diaryId')
user_id = validated_data.pop('userId')
try:
user = User.objects.get(pk=user_id)
except User.DoesNotExist:
raise serializers.ValidationError("유저가 존재하지 않습니다.")
# diaryId가 존재하는지 확인
is_diary_exist = Diary.objects.filter(id=self.data['diaryId']).exists()
# 존재하지 않는다면 False, 404 반환
if not is_diary_exist:
self._errors['diaryId'] = [f'diaryId: {self.data.get("diaryId")} 가 존재하지 않습니다.']
return False, status.HTTP_404_NOT_FOUND

validated_data['user'] = user
content_data = validated_data.pop('content')
new_diary = Diary.objects.create(**validated_data)
Sentences.objects.create(diary=new_diary, sentence=content_data)
return True, status.HTTP_200_OK

return new_diary

class GetUserRequest(serializers.Serializer):
userId = serializers.IntegerField()

def is_valid(self, raise_exception=False):
super_valid = super().is_valid()
# 유효하지 않다면 False, 400 반환
if not super_valid:
return False, status.HTTP_400_BAD_REQUEST

# userId가 존재하는지 확인
is_user_exist = User.objects.filter(id=self.data['userId']).exists()
# 존재하지 않는다면 False, 404 반환
if not is_user_exist:
self._errors['userId'] = [f'userId: {self.data.get("userId")} 가 존재하지 않습니다.']
return False, status.HTTP_404_NOT_FOUND

return True, status.HTTP_200_OK


class GetDiaryRequest(serializers.Serializer):
diaryId = serializers.IntegerField()
diaryId = serializers.IntegerField()

def is_valid(self, raise_exception=False):
super_valid = super().is_valid()
# 유효하지 않다면 False, 400 반환
if not super_valid:
return False, status.HTTP_400_BAD_REQUEST

# diaryId가 존재하는지 확인
is_diary_exist = Diary.objects.filter(id=self.data['diaryId']).exists()
# 존재하지 않는다면 False, 404 반환
if not is_diary_exist:
self._errors['diaryId'] = [f'diaryId: {self.data.get("diaryId")} 가 존재하지 않습니다.']
return False, status.HTTP_404_NOT_FOUND

return True, status.HTTP_200_OK
38 changes: 18 additions & 20 deletions diary/textrank.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ def __init__(self, sentence):
# 단어 가중치 그래프, 단어 사전 을 저장 && 단어 사전 = {index: 단어}
self.words_graph_vocab = np.dot(cnt_vec_mat.T, cnt_vec_mat), {vocab[word]: word for word in vocab}

def get_sent_graph_vocab(self):
return self.sent_graph_vocab
# def get_sent_graph_vocab(self):
# return self.sent_graph_vocab

def get_words_graph_vocab(self):
return self.words_graph_vocab
Expand Down Expand Up @@ -118,26 +118,24 @@ def __init__(self, content):
# 명사 추출
nouns = SentenceTokenizer.get_nouns(self.sentences)

# 가중치 그래프 객체 생성
matrix = GraphMatrix(nouns)
# 문장별 가중치 그래프
sent_graph, snet_vocab = matrix.get_sent_graph_vocab()
# 단어별 가중치 그래프
words_graph, word_vocab = matrix.get_words_graph_vocab()

# (문장, index, 가중치) 리스트 생성
sent_rank = [(snet_vocab[index], index, weight) for index, weight in Rank.get_ranks(sent_graph).items()]
# weight 기준으로 정렬
self.sorted_sent_rank = sorted(sent_rank, key=lambda k: k[2], reverse=True)

# (단어, index, 가중치) 리스트 생성
word_rank_idx = [(word_vocab[index], index, weight) for index, weight in Rank.get_ranks(words_graph).items()]
# weight 기준으로 정렬
self.sorted_word_rank = sorted(word_rank_idx, key=lambda k: k[2], reverse=True)
if nouns:
# 가중치 그래프 객체 생성
matrix = GraphMatrix(nouns)
# 문장별 가중치 그래프 [문장수, 문장수], {index: 문장} 사전
# sent_graph, sent_vocab = matrix.get_sent_graph_vocab()
# 단어별 가중치 그래프 [단어수, 단어수], {index: 단어} 사전
words_graph, word_vocab = matrix.get_words_graph_vocab()

# (단어, index, 가중치) 리스트 생성
word_rank_idx = [(word_vocab[index], index, weight) for index, weight in Rank.get_ranks(words_graph).items()]
# weight 기준으로 정렬
self.sorted_word_rank = sorted(word_rank_idx, key=lambda k: k[2], reverse=True)
else:
self.sorted_word_rank = []

# sent_size 개의 문장 요약
def summarize(self, sent_size=3):
return [sentence for sentence, index, weight in self.sorted_sent_rank[:sent_size]]
# def summarize(self, sent_size=3):
# return [sentence for sentence, index, weight in self.sorted_sent_rank[:sent_size]]

def get_keywords(self, keyword_size=3):
# 단어 가중치 상위 word_size개 word만 추출
Expand Down
8 changes: 3 additions & 5 deletions diary/urls.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from .views import DiaryView, WriteView, GetDiarybyUserView, GetQuizView, UpdateView
from django.urls import path
from .views import WriteView, GetDiaryByUserView, GetQuizView, UpdateView

urlpatterns = [
path('', DiaryView.as_view()),
path('write', WriteView.as_view()),
path('list', GetDiarybyUserView.as_view()),
path('list', GetDiaryByUserView.as_view()),
path('quiz', GetQuizView.as_view()),
path('update', UpdateView.as_view())
]
Loading

0 comments on commit bacba26

Please sign in to comment.