Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/master'
Browse files Browse the repository at this point in the history
  • Loading branch information
anEleftheriadis committed May 7, 2023
2 parents 1a22175 + ff642bb commit 484f590
Show file tree
Hide file tree
Showing 26 changed files with 102 additions and 49 deletions.
29 changes: 16 additions & 13 deletions backend/api/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,20 @@
from fastapi import HTTPException
from fastapi import Request
from fastapi.middleware.cors import CORSMiddleware
# from .. import api
import sys
import time

import os
import sys
parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.insert(0, parent_dir)

from backend_core.dfs import run


from typing import Callable, Any, Tuple

sys.path.append("/backend/core")

sys.path.append("/backend/backend_core/dfs")
# import canvas
app = FastAPI()

Expand Down Expand Up @@ -59,16 +66,12 @@ async def start_solution(request: Request):
letters = body["letterList"]
is_rotated = body["isRotated"]
print(lines, holes, columns, is_rotated,letters)
# UNCOMMENT AUTO EDW
# TA HOLES THELOUN ME MOD KAI DIV NA GINOUN X,Y
# string_arr,runtime = measure_time(run, letters, canvas.__init__(lines, columns, holes), rotation_allows=is_rotated)
# COMMENT AUTA EDW
string_solution = "FFLLI YFFLI YFTLI YFTLI YTTTI"
string_arr = [string_solution]
# EDW PAEI STO SOLUTIONS TA POLLA STO SOLUTION TO MONO(TO SOLUTION DEN EINAI ANAGKAIO ISA ISA TO EKANA COMMENT OUT APO
# TO FRONTEND)
# STO FRONTEND EXW KANEI DUPLICATE GIA NA MPOROYME NA VLEPOUME POLLAPLA THA XREIASTEI NA AFAIRETHEI KATI
return {"message": "POST request succeeded","solutions": string_arr,"time":15.0,"solution":string_solution}
start_time = time.time()
string_arr = run(letters, lines, columns, holes, is_rotated)
end_time = time.time()
print("RUNTIME",end_time-start_time)
runtime = end_time-start_time
return {"message": "POST request succeeded","solutions": string_arr,"time":15.0,"solution":string_arr}


@app.get("/get_saved_data")
Expand Down
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
6 changes: 4 additions & 2 deletions backend/core/canvas.py → backend/backend_core/canvas.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import networkx as nx
import matplotlib.pyplot as plt
from typing import List, Tuple, Callable, Any
from shape import Shape
from backend_core.shape import Shape



Expand Down Expand Up @@ -107,6 +107,8 @@ def count_filled_cells(self) -> int: #not hole or shape

return (the_sum + len(self.holes))

def count_empty_cells(self) -> int:
return (self.dimensions[0] * self.dimensions[1]) - self.count_filled_cells()
def get_all_available_positions(self,s:Shape)->List[Tuple[int,int]]:
matrix_set = set()
for row in range(self.dimensions[0]):
Expand Down Expand Up @@ -156,7 +158,7 @@ def get_all_non_available_positions(self,s:Shape)->List[Tuple[int,int]]:

return list(set(positions))

def get_sring_of_matrix(self):
def get_string_of_matrix(self):
matrix = self.get_matrix()
my_string = ""
for i in matrix:
Expand Down
35 changes: 29 additions & 6 deletions backend/core/dfs.py → backend/backend_core/dfs.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import List, Tuple, Callable, Any
import copy
from shape import Shape
from canvas import Canvas
from backend_core.shape import Shape
from backend_core.canvas import Canvas
import networkx as nx
import time
class Dfs():
Expand Down Expand Up @@ -101,7 +101,7 @@ def measure_time(func: Callable[..., Any], *args: Tuple[Any], **kwargs: Any) ->
#print(f"Function {func.__name__} took {running_time:.6f} seconds to run.")
return result, running_time

def run():
def run(let: List[str], li: int, col: int, hol:List[str] , rot_all: bool = True):
# x, y = 15, 15
#letters = [("F", 3), ("I", 5), ("L", 4), ("N", 4), ("P", 3), ("T", 3), ("U", 2), ("V", 3), ("W", 3), ("X", 3), ("Y", 4), ("Z", 3)]
# root = NodeT(["T", "F", "I", "Y", "L"], Canvas(5, 5, []))
Expand All @@ -117,11 +117,34 @@ def run():
# for i in children:
# frontier.append(i)
#leafs = dfs(["T", "F", "I", "Y", "L"], Canvas(5, 5, []))
leafs, time = measure_time(dfs, ["T", "F", "I", "Y", "L"], Canvas(5, 5, []))

holes = []
# const
# x_values = holes.map((hole) = > hole % columns)
# const
# y_values = holes.map((hole) = > Math.floor(hole / columns))
for hole in hol:
holes.append((int(hole) % col, int(hole) // col))







letters = let
lines = li
columns = col

rotation_allows = rot_all
leafs = dfs(letters, Canvas(lines, columns, holes), rotation_allows)
solutions = []
for i in leafs:
if i.shapes_remain == []:
print(i.canvas.get_matrix(), "\n")
print(time)
if i.canvas.count_empty_cells() == 0:
solutions.append(i.canvas.get_string_of_matrix())

return list(set(solutions))

run()
#print(run(["T", "F", "I"], 5, 5, ["0", "6"], True))
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
File renamed without changes.
2 changes: 1 addition & 1 deletion backend/core/shape.py → backend/backend_core/shape.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import matplotlib.pyplot as plt
from typing import List, Tuple, Callable, Any
#from canvas import Canvas
from node import Node
from backend_core.node import Node

class Shape():

Expand Down
File renamed without changes.
70 changes: 48 additions & 22 deletions frontend/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import BlankCanvas from './components/BlankCanvas'
import ChooseLetters from './components/ChooseLetters'
import ShowSelectedLetters from './components/ShowSelectedLetters'
import SaveConfiguration from './components/SaveConfiguration.jsx'
import DownloadSolution from './components/DownloadSolution'
import DownloadSolutions from './components/DownloadSolutions'
import LoadConfiguration from './components/LoadConfiguration'

type CellData = {
Expand All @@ -31,6 +31,7 @@ function App() {
const [multipleResults, setResults] = useState<CellData[][]>([])
const [time, setTime] = useState<string>("")
const [isRotated, setIsRotated] = useState<boolean>(false)
const [downloadSolutions, setDownloadSolutions] = useState<string[]>([])
const handleCellClick = (index: number) => {
console.log("cell clicked", index)
if (holes.includes(index)) {
Expand Down Expand Up @@ -67,8 +68,8 @@ function App() {
holes_coordinates.push([x_values[i], y_values[i]])
}


console.log("holes_coordinates", holes_coordinates)
let total_result: any[] = []
//console.log("holes_coordinates", holes_coordinates)
const data = {
rows: rows,
columns: columns,
Expand All @@ -77,35 +78,60 @@ function App() {
isRotated: isRotated
}
console.log("data", data)
const response = await fetch(`http://localhost:${api_port}/${api_route}`, {
const response = fetch(`http://localhost:${api_port}/${api_route}`, {
method: "POST",
headers: {
"Content-Type": "application/json",
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify(data),
}).then((response) => {
return response.json()
}).then((res: any) => {
console.log(res)
const time = res.time as string;
const solutions = res.solutions as string[];
total_result = solutions.map((solution: string) => {
return Array.from(solution.replace(/ /g, "")).map((letter, index) => {
return {
size: pixels,
bgcolor: "red",
isRemovedForHole: false,
index: index,
letter: letter
}


})
})
setDownloadSolutions(solutions)
setResults(total_result)
setTime(time)
}).catch((err: any) => {
console.log(err)
})



console.log("response", response)
const result = await response.json()
console.log(result)
const solution = result.solution as string;
const total_result = Array.from(solution.replace(/ /g, "")).map((letter, index) => {
return {
size: pixels,
bgcolor: "red",
isRemovedForHole: false,
index: index,
letter: letter
}
})

console.log("TOTAL RESULT IS", total_result)
// setResult(total_result)
setResults([total_result, total_result])
setTime(result.time)
// console.log("response", response)
// // const result = await response.json()
// console.log(result)
// const solution = result.solution as string;
// const total_result = Array.from(solution.replace(/ /g, "")).map((letter, index) => {
// return {
// size: pixels,
// bgcolor: "red",
// isRemovedForHole: false,
// index: index,
// letter: letter
// }
// })

// console.log("TOTAL RESULT IS", total_result)
setResult(total_result)

// setTime(result.time)
// update state with response

// console.log("data", data)
Expand Down Expand Up @@ -147,7 +173,7 @@ function App() {
})}
<DisplaySolution cellsData={result} columns={columns} rows={rows} />
<br />
<DownloadSolution results={result} />
<DownloadSolutions results={downloadSolutions} />
<br />
</div>
)
Expand Down
3 changes: 1 addition & 2 deletions frontend/src/components/Canvas.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ function Canvas({ cellsData, handleCellClick, rows, columns }: { cellsData: Cell
<div style={style}>

{cellsData.map((cellData) => {
console.log(cellData)

return <span><Cell holeColor='black' size={cellData.size} key={cellData.letter + "1"} bgcolor={cellData.bgcolor} isRemovedForHole={cellData.isRemovedForHole} index={cellData.index} letter={cellData.letter} handleCellClick={(e) => console.log("nothing")
} /></span>
})}
Expand Down Expand Up @@ -64,7 +64,6 @@ export function Cell({ size = 20, bgcolor = "white", isRemovedForHole, holeColor
let the_index = -1;
for (let i = 0; i < supportedLetters.length; i++) {
if (letter === supportedLetters[i]) {
console.log("letter is: ", letter, "and color is: ", letterColors[i])
the_index = i;
break;
}
Expand Down
2 changes: 0 additions & 2 deletions frontend/src/components/ChooseLetters.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,11 +19,9 @@ function ChooseLetters({ letterList, setLetterList }: { letterList: string[], se
]

const handleLetterClick = (letter: string) => {
console.log(letter)
setLetterList(prev => [...prev, letter])
}

console.log(letterList)


return (
Expand Down
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import { CellData } from "./Canvas";

const DownloadSolution = ({ results }: { results: any }) => {
const DownloadSolution = ({ results }: { results: string[] }) => {

const handleDownload = () => {
const element = document.createElement("a");

const file = new Blob([JSON.stringify(results)], { type: 'application/json' });
element.href = URL.createObjectURL(file);
element.download = "results.json";
Expand Down
Empty file removed frontend/src/components/TIme.tsx
Empty file.

0 comments on commit 484f590

Please sign in to comment.