Skip to content

Commit

Permalink
Merge branch 'main' into create_single_corpus_component
Browse files Browse the repository at this point in the history
  • Loading branch information
phuang00 committed Jul 19, 2021
2 parents f2fd0e1 + e0d24bc commit ddfa24d
Show file tree
Hide file tree
Showing 6 changed files with 147 additions and 16 deletions.
3 changes: 3 additions & 0 deletions backend/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -539,3 +539,6 @@ def __eq__(self, other):
return False

return list(self.documents.values_list('pk', flat=True)) == list(other.documents.values_list('pk', flat=True))

def __hash__(self):
return super().__hash__()
2 changes: 1 addition & 1 deletion backend/app/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ class DocumentSerializer(serializers.ModelSerializer):

class Meta:
model = Document
fields = ['id', 'author', 'title', 'year', 'text', 'word_count']
fields = ['id', 'author', 'title', 'year', 'text', 'word_count', 'new_attributes']


class SimpleDocumentSerializer(serializers.ModelSerializer):
Expand Down
75 changes: 71 additions & 4 deletions backend/app/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,12 +27,14 @@
from django.shortcuts import render
from .models import (
Document,
Gender
Gender,
Corpus
)
from .serializers import (
DocumentSerializer,
SimpleDocumentSerializer,
GenderSerializer
GenderSerializer,
CorpusSerializer
)


Expand Down Expand Up @@ -101,11 +103,17 @@ def add_document(request):
API endpoint for adding a piece of document
"""
attributes = request.data
new_attributes = {}
for attribute in attributes['newAttributes']:
key, value = attribute['name'], attribute['value']
if key and value:
new_attributes[key] = value
fields = {
'title': attributes['title'],
'author': attributes['author'],
'year': attributes['year'] if attributes['year'] != '' else None,
'text': attributes['text']
'text': attributes['text'],
'new_attributes': new_attributes
}
new_text_obj = Document.objects.create_document(**fields)
serializer = DocumentSerializer(new_text_obj)
Expand Down Expand Up @@ -175,6 +183,66 @@ def all_genders(request):
return Response(serializer.data)


@api_view(['POST'])
def add_corpus(request):
"""
API endpoint for adding a corpus instance
"""
attributes = request.data
fields = {
'title': attributes['title'],
'description': attributes['description']
}
new_corpus_obj = Corpus.objects.create(**fields)
serializer = CorpusSerializer(new_corpus_obj)
return Response(serializer.data)


@api_view(['POST'])
def update_corpus_docs(request):
"""
API endpoint for updating the documents in a corpus
"""
corpus_data = request.data
corpus_id = corpus_data['id']
doc_ids = corpus_data['documents']
corpus_obj = Corpus.objects.get(id=corpus_id)
corpus_obj.documents.set(Document.objects.filter(id__in=doc_ids))
serializer = CorpusSerializer(corpus_obj)
return Response(serializer.data)


@api_view(['DELETE'])
def delete_corpus(request):
"""
API endpoint for deleting a corpus
"""
corpus_id = request.data['id']
corpus_obj = Corpus.objects.get(id=corpus_id)
res = corpus_obj.delete()
return Response(res)


@api_view(['GET'])
def all_corpora(request):
"""
API endpoint to get all the corpora
"""
corpus_objs = Corpus.objects.all()
serializer = CorpusSerializer(corpus_objs, many=True)
return Response(serializer.data)


@api_view(['GET'])
def get_corpus(request, corpus_id):
"""
API endpoint to get a corpus based on id
"""
corpus_obj = Corpus.objects.get(id=corpus_id)
serializer = CorpusSerializer(corpus_obj)
return Response(serializer.data)


def corpus(request, corpus_id):
"""
Corpus Page
Expand All @@ -191,4 +259,3 @@ def corpus(request, corpus_id):
}

return render(request, 'index.html', context)

5 changes: 5 additions & 0 deletions backend/config/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@
path('api/add_document', views.add_document),
path('api/document/<int:doc_id>', views.get_document),
path('api/all_genders', views.all_genders),
path('api/all_corpora', views.all_corpora),
path('api/add_corpus', views.add_corpus),
path('api/update_corpus_docs', views.update_corpus_docs),
path('api/delete_corpus', views.delete_corpus),
path('api/corpus/<int:corpus_id>', views.get_corpus),

# View paths
path('', views.index, name='index'),
Expand Down
76 changes: 66 additions & 10 deletions frontend/components/Documents.js
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ const Documents = () => {
"year": "",
"text": ""
});
const [newAttributes, setNewAttributes] = useState([{"name": "", "value": ""}]);
const [loading, setLoading] = useState(true);
const [addingDoc, setAddingDoc] = useState(false);
const [showModal, setShowModal] = useState(false);
Expand Down Expand Up @@ -56,6 +57,25 @@ const Documents = () => {
}));
};

const handleAttributeInputChange = (event, index) => {
const {name, value} = event.target;
setNewAttributes(prevAttributes => {
return prevAttributes.map((attribute, i) => {
return i === index ? {...attribute, [name]:value} : attribute;
});
});
};

const handleAddAttribute = () => {
setNewAttributes([...newAttributes, {"name": "", "value": ""}]);
};

const handleRemoveAttribute = (index) => {
setNewAttributes(previousAttributes => (
previousAttributes.filter((attribute, idx) => idx !== index)
));
};

const handleSubmit = (event) => {
event.preventDefault();
setAddingDoc(true);
Expand All @@ -71,7 +91,8 @@ const Documents = () => {
title: newDocData.title,
year: newDocData.year,
author: newDocData.author,
text: newDocData.text
text: newDocData.text,
newAttributes: newAttributes
})
};
fetch("api/add_document", requestOptions)
Expand All @@ -95,7 +116,7 @@ const Documents = () => {
<div className="card-body">
<h6 className="mb-0">{doc.title}</h6>
<p>
{doc.author}
{doc.author ? doc.author : "Unknown"}
<br/>
Year Published: {doc.year ? doc.year : "Unknown"}
<br/>
Expand Down Expand Up @@ -144,7 +165,7 @@ const Documents = () => {
<div className="col">
<input type="text" className="form-control"
id="title" value={newDocData.title}
onChange={handleTitleInputChange}/>
onChange={handleTitleInputChange} required/>
</div>
</div>
<div className="row mb-3">
Expand All @@ -166,9 +187,47 @@ const Documents = () => {
onChange={handleTextInputChange} required></textarea>
</div>
</div>
<p>Attributes</p>
{
newAttributes.map((attribute, i) => {
return (
<div key={i} className="row mb-3">
<div className="col-4">
<input type="text" className="form-control"
name="name" onChange={event =>
handleAttributeInputChange(event,i)}
placeholder="name" value={attribute.name}
required={newAttributes[i]["value"]
? true : false}/>
</div>
<div className="col-3">
<input type="text" className="form-control"
name="value" onChange={event =>
handleAttributeInputChange(event,i)}
placeholder="value" value={attribute.value}
required={newAttributes[i]["name"]
? true : false}/>
</div>
{newAttributes.length !== 1 &&
<div className="col">
<button type="button"
onClick={() => handleRemoveAttribute(i)}
className="btn btn-secondary">
Remove </button>
</div>}
{newAttributes.length - 1 === i &&
<div className="col">
<button type="button"
onClick={handleAddAttribute}
className="btn btn-primary">Add</button>
</div>}
</div>
);
})
}
</Modal.Body>
<Modal.Footer>
<button className="btn btn-secondary"
<button className="btn btn-secondary" type="button"
onClick={handleCloseModal}>Close</button>
<button className="btn btn-primary"
type="submit">Add</button>
Expand All @@ -185,12 +244,9 @@ const Documents = () => {
<p>
This page displays all the documents stored in backend.
</p>
{
addingDoc
? <div className="alert alert-warning" role="alert">
Currently adding document... Please do not close this tab.
</div>
: null
{addingDoc && <div className="alert alert-warning" role="alert">
Currently adding document... Please do not close this tab.
</div>
}
{addDocModal()}
{
Expand Down
2 changes: 1 addition & 1 deletion frontend/components/SingleDocument.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ const SingleDocument = ({id}) => {
: <div>
<h1>{docData.title}</h1>
<p>
Author: {docData.author}
Author: {docData.author ? docData.author : "Unknown"}
<br/>
Year Published {docData.year ? docData.year : "Unknown"}
<br/>
Expand Down

0 comments on commit ddfa24d

Please sign in to comment.