Skip to content

Commit

Permalink
Search get api changed, minor refactorings.
Browse files Browse the repository at this point in the history
  • Loading branch information
ani-hovhannisyan committed Aug 29, 2024
1 parent 0f6dbae commit 7e1c0cb
Show file tree
Hide file tree
Showing 8 changed files with 58 additions and 43 deletions.
2 changes: 1 addition & 1 deletion backend/config.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# This is the file containing configurations

# TODO: Replace the yama.json to all kanji json file or call a remote API
KANJI_DATA_FILE = "./backend/tests/graph-controller/test_kanji_all_data.json"
KANJI_DATA_FILE = "tests/graph-controller/test_kanji_all_data.json"
51 changes: 25 additions & 26 deletions backend/controller/GraphController.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# This is the Graph Controller class implementation.
# TODO: Remove the json if
import os
import json
import config
from controller.SearchController import SearchController
Expand Down Expand Up @@ -34,21 +35,19 @@ def create_links(kanji, word):
@staticmethod
def construct_nodes_json(kanji, words):
words_list = list(dict.fromkeys(words))
json = {"nodes": [], "links": [], "words": words_list}
djson = {"nodes": [], "links": [], "words": words_list}
if len(words) > 1: # No other words or one specified main kanji is
for word in words:
if len(word) > 1:
if SearchController._is_kanji(word): # Skip okurigana
json["nodes"] = json["nodes"] + GraphController.create_nodes(
kanji, word, json["nodes"]
)
json["links"] = json["links"] + GraphController.create_links(
kanji, word
)
json["nodes"].append({"id": kanji, "isMain": "true"})
djson["nodes"] = djson["nodes"] + GraphController.create_nodes(
kanji, word, djson["nodes"])
djson["links"] = djson["links"] + GraphController.create_links(
kanji, word)
djson["nodes"].append({"id": kanji, "isMain": "true"})
else:
print("Can't find any word from the DB for specified kanji.")
return json
return djson

@staticmethod
# TODO: It might happen to have same kanji with different reading, current
Expand All @@ -72,28 +71,28 @@ def get_words_data(kanji, data):
word = worda["japanese"].split("(")[0]
if not words.count(word):
words.append(word)
# TODO: Keep occurences of same word

return GraphController.construct_nodes_json(kanji, words)

# TODO: Adding more static methods replace if necessary in #58
@staticmethod
def load_local_db(kanji):
# TODO: Put try catch for unexpected DB file and json format
f = open(config.KANJI_DATA_FILE)
localDB = json.loads(f.read())
data = {}
for entity in localDB:
if kanji == entity:
data = GraphController.get_words_data(kanji, localDB[entity])
break
return data

# TODO: As this method will open the data file each time make it one time
@staticmethod
def get_graph_matrix(kanji: str):
try:
graph_matrix = GraphController.load_local_db(kanji)
return [True, None, graph_matrix]
data = {}
if not os.path.exists(config.KANJI_DATA_FILE):
print("Can not read config file:", config.KANJI_DATA_FILE)
return data
f = open(config.KANJI_DATA_FILE)
localDB = json.loads(f.read())
return [True, localDB]
except ValueError as e:
error_info = {"status_code": 400, "detail": e}
return [False, error_info, None]
return [False, error_info]

@staticmethod
def get_graph_matrix(kanji, db):
graph_matrix = {}
for entity in db:
if kanji == entity:
graph_matrix = GraphController.get_words_data(kanji, db[entity])
return [True, None, graph_matrix]
32 changes: 24 additions & 8 deletions backend/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,24 +19,40 @@

@app.get("/")
def read_root():
return {"message": "Hello from FastAPI!"}
return {"message": "Hi, Kanji-Visualization Server FAST API works fine!"}


@app.get("/kanji-visualize")
def read_kanji_visualize(kanji: str):
print("Got request to search kanji:", kanji)
@app.get("/kanjidata")
async def read_kanji_visualize(kanji: str):
"""
Search kanji by character.
Args:
kanji (str): The Japanese language single character.
Returns:
json: A json containing character details.
"""

# print("Got request to search kanji:", kanji)

is_success, error_info = SearchController.check_input(kanji)
print("API /kanji-visualize got error:", error_info)
if error_info:
print("API /kanjidata got error:", error_info)

if not is_success:
raise HTTPException(**error_info)

# TODO: Think of moving local DB loading to the top of server run
is_success, error_info, graph_json = GraphController.get_graph_matrix(kanji)
is_db_success, data = GraphController.load_local_db(kanji)
if not is_db_success:
raise HTTPException(**data)

is_success, error_info, graph_json = GraphController.get_graph_matrix(kanji, data)
if not is_success:
raise HTTPException(**error_info)

is_success, error_info, kanji_info = InfoController.get_kanji_info(kanji)
if not is_success:
raise HTTPException(**error_info)

return {**graph_json, **kanji_info}
result = {**graph_json, **kanji_info}

return result
1 change: 0 additions & 1 deletion docker-compose.yml
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
version: '3'
services:
backend:
build:
Expand Down
4 changes: 2 additions & 2 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -14,8 +14,8 @@ function App() {
const [graph, setGraph] = useState<undefined | GraphMatrix>();
const [loading, setLoading] = useState<boolean>(false);

//console.log("Inputed kanji is:", kanjiInput);
//console.log("Kanji inforamtion is:", kanji);
//console.log("Input kanji is:", kanjiInput);
//console.log("Kanji information is:", kanji);
//console.log("Kanji graph is:", graph);

return (
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/GraphView/GraphView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ const GraphView: React.VFC<Props> = (props) => {
{ width, height }
);

const padding = 16;
const padding = 8;

useEffect(() => {
const graphViewTop =
Expand Down
7 changes: 4 additions & 3 deletions frontend/src/components/InfoView/InfoView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,10 @@ const InfoView: React.VFC<Props> = (props) => {
//console.log("In InfoView, received kanji info is:", info);

const info = props.infoData;
const lang = "English"; // Use this when other languages become supported
// Use this when other languages become supported
const lang = "English";

const joinToStr = (arr: string[]) => arr.join().replace(",", ", ");
const joinToStr = (arr: string[]) => arr.join(", ")

const createData = (name: string, value: string) => {
return { name, value };
Expand Down Expand Up @@ -56,7 +57,7 @@ const InfoView: React.VFC<Props> = (props) => {
sx={{ flexGrow: 1, padding: "1rem" }}
>
<Typography variant="h5" component="h2">
The {info?.id} kanji Information
Details
</Typography>
{table}
</Paper>
Expand Down
2 changes: 1 addition & 1 deletion frontend/src/components/SearchField/SearchField.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ const SearchField: React.VFC<Props> = (props) => {

axios
.get(
`${process.env.REACT_APP_API_URL}:${process.env.REACT_APP_API_PORT}/kanji-visualize?kanji=${props.kanjiInput}`
`${process.env.REACT_APP_API_URL}:${process.env.REACT_APP_API_PORT}/kanjidata?kanji=${props.kanjiInput}`
)
.then((res) => {
props.setLoading(false);
Expand Down

0 comments on commit 7e1c0cb

Please sign in to comment.