Skip to content

Commit

Permalink
fixes #5
Browse files Browse the repository at this point in the history
  • Loading branch information
WolfgangFahl committed Aug 17, 2023
1 parent bc6a6f4 commit 747dfc4
Show file tree
Hide file tree
Showing 6 changed files with 112 additions and 27 deletions.
45 changes: 45 additions & 0 deletions nicesrt/geo.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
@author: wf
'''
from typing import List, Tuple
import math

class GeoPath:
def __init__(self):
Expand All @@ -16,3 +17,47 @@ def add_point(self, lat: float, lon: float) -> None:
def get_path(self) -> List[Tuple[float, float]]:
"""Return the path."""
return self.path

def haversine_distance(self, point1: Tuple[float, float], point2: Tuple[float, float]) -> float:
"""Calculate the Haversine distance between two points."""
# Radius of the Earth in kilometers
R = 6371.0

# Convert degrees to radians
lat1 = math.radians(point1[0])
lon1 = math.radians(point1[1])
lat2 = math.radians(point2[0])
lon2 = math.radians(point2[1])

# Differences in coordinates
dlat = lat2 - lat1
dlon = lon2 - lon1

# Haversine formula
a = math.sin(dlat / 2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2)**2
c = 2 * math.atan2(math.sqrt(a), math.sqrt(1 - a))

# Distance in kilometers
distance = R * c
return distance

def distance(self, index1: int, index2: int) -> float:
"""Calculate the distance along the path from point at index1 to index2."""
# Validate indices
if index1 < 0 or index1 >= len(self.path) or index2 < 0 or index2 >= len(self.path):
raise ValueError("Invalid indices provided")

# Ensure index1 is less than index2
index1, index2 = min(index1, index2), max(index1, index2)

total_distance = 0
for i in range(index1, index2):
total_distance += self.haversine_distance(self.path[i], self.path[i+1])

return total_distance

def total_distance(self)->float:
total_distance=0
if len(self.path)>1:
total_distance=self.distance(0, len(self.path)-1)
return total_distance
8 changes: 2 additions & 6 deletions nicesrt/srt.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,6 @@
from nicesrt.geo import GeoPath
import re

import pysrt
from nicesrt.geo import GeoPath
import re

class SRT:
"""
Class to represent and manipulate SRT (SubRip Subtitle) data.
Expand Down Expand Up @@ -59,9 +55,9 @@ def extract_value(self, index, key):
# Search using the bracketed value pattern
matches = re.findall(self.patterns['bracketed_value'], text)
for k, v1, v2, _ in matches:
if k in ["GPS", "HOME"] and key == "latitude":
if k in ["GPS"] and key == "latitude":
return v1
elif k in ["GPS", "HOME"] and key == "longitude":
elif k in ["GPS"] and key == "longitude":
return v2

return result
Expand Down
7 changes: 4 additions & 3 deletions nicesrt/webserver.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ async def reload_file(self):
self.examples_path(),
self.root_path
]
allowed=False
allowed=self.is_local
if not self.is_local:
for allowed_url in allowed_urls:
if input_str.startswith(allowed_url):
Expand All @@ -160,20 +160,21 @@ async def reload_file(self):
else:
await self.read_and_optionally_render(self.input)

def link_button(self, name: str, target: str, icon_name: str):
def link_button(self, name: str, target: str, icon_name: str,new_tab:bool=True):
"""
Creates a button with a specified icon that opens a target URL upon being clicked.
Args:
name (str): The name to be displayed on the button.
target (str): The target URL that should be opened when the button is clicked.
icon_name (str): The name of the icon to be displayed on the button.
new_tab(bool): if True open link in new tab
Returns:
The button object.
"""
with ui.button(name,icon=icon_name) as button:
button.on("click",lambda: (ui.open(target)))
button.on("click",lambda: (ui.open(target,new_tab=new_tab)))
return button


Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ dependencies = [
# nicegui
# fastapi
# uvicorn
"nicegui>=1.3.5",
"nicegui>=1.3.9",
# pysrt
"pysrt"
]
Expand Down
33 changes: 33 additions & 0 deletions tests/test_geo.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
'''
Created on 2023-08-17
@author: wf
'''
from nicesrt.geo import GeoPath
from tests.basetest import Basetest

class Test_GeoPath(Basetest):
"""
Test the GeoPath functions
"""

def setUp(self, debug=False, profile=True):
Basetest.setUp(self, debug=debug, profile=profile)

def test_distance(self):
"""
test haversine distance calculation
"""
geo_path = GeoPath()
geo_path.add_point(52.5200, 13.4050) # Berlin
geo_path.add_point(48.8566, 2.3522) # Paris
geo_path.add_point(51.5074, -0.1278) # London
berlin_paris=geo_path.distance(0, 1)
berlin_london=geo_path.total_distance()
debug=self.debug
debug=True
if (debug):
print(f"Berlin-Paris: {berlin_paris:.0f} km")
print(f"Berlin-Paris-London: {berlin_london:.0f} km")
self.assertAlmostEqual(877,berlin_paris,delta=1)
self.assertAlmostEqual(1221,berlin_london,delta=1)
44 changes: 27 additions & 17 deletions tests/test_srt.py
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,23 @@ def test_srt(self):
self.assertAlmostEqual(g_lat, lat, delta=delta)
self.assertAlmostEqual(g_lon, lon, delta=delta)


def check_sample(self,srt_file_url:str,hint:str,debug:bool=True):
response = requests.get(srt_file_url)
response.raise_for_status()

srt_text = response.text
file_name = srt_file_url.split('/')[-1]
self.check_text(srt_text,hint,file_name,debug)

def check_text(self,srt_text,hint,file_name,debug):
srt=SRT.from_text(srt_text)
geo_path=srt.as_geopath()
total_distance=geo_path.total_distance()

if debug:
print(f"{hint}:{len(geo_path.path)}:{total_distance:.3f} km:{file_name}")

def test_drone_videos(self):
"""
Test method to check all SRT files from the `/Volumes/Dronevideos` directory.
Expand All @@ -77,16 +94,16 @@ def test_drone_videos(self):
dronevideos_path = "/Volumes/Dronevideos"

if os.path.exists(dronevideos_path):
for filename in os.listdir(dronevideos_path):
for i,filename in enumerate(os.listdir(dronevideos_path)):
if filename.endswith(".SRT"):
with open(os.path.join(dronevideos_path, filename), 'r', encoding='utf-8') as file:
text = file.read()

# Create an SRT object and extract its GeoPath
srt_obj = SRT.from_text(text)
geo_path = srt_obj.as_geopath()
print(f"{filename}:{len(geo_path.path)}")
srt_text = file.read()
self.check_text(srt_text, hint=f"{i:2}", file_name=filename, debug=True)

def test_sample(self):
sample_url="https://raw.githubusercontent.com/JuanIrache/dji-srt-viewer/master/samples/sample4.SRT"
self.check_sample(sample_url,"sample4",debug=True)

def test_samples(self):
"""
test JuanIrache samples
Expand All @@ -101,13 +118,6 @@ def test_samples(self):

for i,srt_file_url in enumerate(srt_files):
t=len(srt_files)
response = requests.get(srt_file_url)
response.raise_for_status()

srt_text = response.text
srt=SRT.from_text(srt_text)
geo_path=srt.as_geopath()
file_name = srt_file_url.split('/')[-1]
if debug:
print(f"{ir+1}:{i+1:2d}/{t:2d}:{len(geo_path.path)}:{file_name}")
hint=f"{ir+1}:{i+1:2d}/{t:2d}"
self.check_sample(srt_file_url,hint,debug)

0 comments on commit 747dfc4

Please sign in to comment.