Skip to content

Commit 1f27f46

Browse files
committed
refactor: follow pep8 function naming
1 parent 60c4afe commit 1f27f46

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

49 files changed

+396
-397
lines changed

lires/api/server.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
from typing import TYPE_CHECKING, Optional, Any, Literal, TypedDict
44
import aiohttp, json, os
55
import deprecated
6-
from lires.utils import randomAlphaNumeric
6+
from lires.utils import random_alphanumeric
77
from lires.types.dataT import DataPointSummary
88
if TYPE_CHECKING:
99
from lires.core.dataClass import DataPointSummary
@@ -27,7 +27,7 @@ def __init__(
2727
self._verify_ssl = verify_ssl
2828
if session_id is None:
2929
self._session_id = "default"
30-
self._session_id = 'py-api-'+randomAlphaNumeric(8)
30+
self._session_id = 'py-api-'+random_alphanumeric(8)
3131

3232
@property
3333
def token(self): return self._token

lires/cmd/_update_db.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
import os, shutil, tqdm, asyncio
55
from lires.utils import TimeUtils
66
from lires.core.dbConn import DBConnection, DocInfo
7-
from lires.core.bibReader import parseBibtex
7+
from lires.core.bibReader import parse_bibtex
88
from lires.core.dbConn_ import DBConnection as DBConnection_old
99
from lires.core.dbConn_ import DocInfo as DocInfo_old
1010
from lires.config import TMP_DIR, DATABASE_DIR
@@ -17,7 +17,7 @@ async def sync(conn: DBConnection, conn_old: DBConnection_old):
1717
all_entries = await conn_old.getMany(all_uids)
1818

1919
for old_entry in tqdm.tqdm(all_entries):
20-
bib = await parseBibtex(old_entry["bibtex"])
20+
bib = await parse_bibtex(old_entry["bibtex"])
2121
old_info = DocInfo_old.fromString(old_entry["info_str"])
2222
new_info = DocInfo(
2323
uuid = old_info.uuid,
@@ -27,7 +27,7 @@ async def sync(conn: DBConnection, conn_old: DBConnection_old):
2727
device_modify=old_info.device_modify,
2828
)
2929

30-
uid = await conn.addEntry(
30+
uid = await conn.add_entry(
3131
bibtex = old_entry["bibtex"],
3232
title = bib["title"],
3333
year = bib["year"],
@@ -47,7 +47,7 @@ async def sync(conn: DBConnection, conn_old: DBConnection_old):
4747
time_import = old_info.time_import
4848
if isinstance(time_import, str):
4949
# backward compatibility, < 0.6.0
50-
time_import = TimeUtils.strLocalTimeToDatetime(time_import).timestamp()
50+
time_import = TimeUtils.localstr2datetime(time_import).timestamp()
5151

5252
await conn.conn.execute(
5353
"""
@@ -64,7 +64,7 @@ async def sync(conn: DBConnection, conn_old: DBConnection_old):
6464
print("Done")
6565

6666
if __name__ == "__main__":
67-
temp_backup = os.path.join(TMP_DIR, "DB_BACKUP_1.4.x_to_1.5.x-{}".format(TimeUtils.nowStamp()))
67+
temp_backup = os.path.join(TMP_DIR, "DB_BACKUP_1.4.x_to_1.5.x-{}".format(TimeUtils.now_stamp()))
6868
# make a backup of the old database
6969
if os.path.exists(temp_backup):
7070
exit("Backup already exists, please remove it first: {}".format(temp_backup))

lires/cmd/cluster.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
from lires.version import VERSION
77
from lires.config import LRS_HOME
8-
from lires.utils import BCOLORS, randomAlphaNumeric
8+
from lires.utils import BCOLORS, random_alphanumeric
99
from typing import TypedDict
1010
import os, argparse, subprocess, signal, time
1111
import re
@@ -32,7 +32,7 @@ def __getDefaultConfig()->ClusterConfigT:
3232
"VERSION": "0.1.0",
3333
"GLOBAL_ENV": {
3434
"LRS_HOME": LRS_HOME,
35-
"LRS_KEY": randomAlphaNumeric(32),
35+
"LRS_KEY": random_alphanumeric(32),
3636
# disable logging to terminal, as it will be messy if the log server are also running
3737
"LRS_TERM_LOG_LEVEL": "CRITICAL",
3838
},

lires/cmd/config.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,12 @@ def run():
2121
print(json.dumps(json.load(fp), indent=1))
2222

2323
elif args.subparser == "edit":
24-
from lires.utils import openFile
24+
from lires.utils import open_file
2525
import subprocess
2626
if args.use_editor:
2727
subprocess.call([args.use_editor, CONF_FILE_PATH])
2828
else:
29-
openFile(CONF_FILE_PATH)
29+
open_file(CONF_FILE_PATH)
3030

3131
else:
3232
parser.print_help()

lires/cmd/index.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55

66
from lires.core.vecutils import build_feature_storage, query_feature_index
77
from lires.api import IServerConn
8-
from lires.loader import initResources
8+
from lires.loader import init_resources
99

1010
def parseArgs() -> argparse.Namespace:
1111
parser = argparse.ArgumentParser(description="Build search index for the database")
@@ -31,9 +31,9 @@ def parseArgs() -> argparse.Namespace:
3131

3232
async def entry(args):
3333

34-
user_pool, db_pool = await initResources()
34+
user_pool, db_pool = await init_resources()
3535
# check if user exists
36-
user = await user_pool.getUserByUsername(args.user)
36+
user = await user_pool.get_user_by_username(args.user)
3737
if user is None:
3838
print(f"Error: User {args.user} does not exist")
3939
await user_pool.close(); await db_pool.close()

lires/cmd/invite.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11

22
import argparse
3-
from lires.loader import initResources
3+
from lires.loader import init_resources
44

55
async def _run():
66
parser = argparse.ArgumentParser()
@@ -18,21 +18,21 @@ async def _run():
1818

1919
args = parser.parse_args()
2020

21-
user_pool, db_pool = await initResources()
21+
user_pool, db_pool = await init_resources()
2222
user_db_conn = user_pool.conn
2323
try:
2424
if args.subparser == "create":
25-
await user_db_conn.createInvitation(
25+
await user_db_conn.create_invitation(
2626
code = args.code,
2727
created_by=0,
2828
max_uses=args.max_uses,
2929
)
3030

3131
elif args.subparser == "delete":
32-
await user_db_conn.deleteInvitation(args.code)
32+
await user_db_conn.delete_invitation(args.code)
3333

3434
elif args.subparser == "list":
35-
for inv in await user_db_conn.listInvitations():
35+
for inv in await user_db_conn.list_invitations():
3636
if not inv["max_uses"] > inv["uses"] and args.valid:
3737
continue
3838

lires/cmd/miscUtils.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,12 @@ def main():
2121
asyncio.run(download_default_pdfjs_viewer(download_url=args.url, dst_dir=PDF_VIEWER_DIR, force=True))
2222
if args.subparser == "edit-config":
2323
from lires.config import CONF_FILE_PATH
24-
from lires.utils import openFile
24+
from lires.utils import open_file
2525
import subprocess
2626
if args.use_editor:
2727
subprocess.call([args.use_editor, CONF_FILE_PATH])
2828
else:
29-
openFile(CONF_FILE_PATH)
29+
open_file(CONF_FILE_PATH)
3030

3131

3232
if __name__ == "__main__":

lires/cmd/userManage.py

Lines changed: 21 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,8 @@
11
import argparse
2-
from lires.loader import initResources
3-
from lires.user.encrypt import generateHexHash
2+
from lires.loader import init_resources
3+
from lires.user.encrypt import generate_hex_hash
44
from lires.core.dataTags import DataTags
5-
from lires.utils import tablePrint, TimeUtils
5+
from lires.utils import table_print, TimeUtils
66

77
def str2bool(v):
88
if isinstance(v, bool):
@@ -58,51 +58,51 @@ def parseStorage(s: str) -> int:
5858

5959
args = parser.parse_args()
6060

61-
user_pool, db_pool = await initResources()
61+
user_pool, db_pool = await init_resources()
6262
user_db_conn = user_pool.conn
6363
try:
6464
if args.subparser == "add":
6565
assert args.password is not None, "Password is required"
66-
await user_db_conn.insertUser(
67-
username=args.username, password=generateHexHash(args.password), name=args.name,
68-
is_admin=args.admin, mandatory_tags=DataTags(args.tags).toOrderedList(),
66+
await user_db_conn.insert_user(
67+
username=args.username, password=generate_hex_hash(args.password), name=args.name,
68+
is_admin=args.admin, mandatory_tags=DataTags(args.tags).to_ordered_list(),
6969
max_storage=parseStorage(args.max_storage) if args.max_storage is not None else None
7070
)
7171

7272
elif args.subparser == "update":
7373
assert args.username is not None, "Username is required"
74-
user_id = (await user_db_conn.getUser(args.username))["id"]
74+
user_id = (await user_db_conn.get_user(args.username))["id"]
7575
if args.password is not None:
76-
await user_db_conn.updateUser(user_id, password=generateHexHash(args.password))
76+
await user_db_conn.update_user(user_id, password=generate_hex_hash(args.password))
7777
if args.name is not None:
78-
await user_db_conn.updateUser(user_id, name=args.name)
78+
await user_db_conn.update_user(user_id, name=args.name)
7979
if args.tags is not None:
80-
await user_db_conn.updateUser(user_id, mandatory_tags=DataTags(args.tags).toOrderedList())
80+
await user_db_conn.update_user(user_id, mandatory_tags=DataTags(args.tags).to_ordered_list())
8181
if args.admin is not None:
82-
await user_db_conn.updateUser(user_id, is_admin=args.admin)
82+
await user_db_conn.update_user(user_id, is_admin=args.admin)
8383
if args.max_storage is not None:
84-
await user_db_conn.updateUser(user_id, max_storage=parseStorage(args.max_storage))
84+
await user_db_conn.update_user(user_id, max_storage=parseStorage(args.max_storage))
8585

8686
elif args.subparser == "delete":
8787
assert args.username is not None or args.id is not None, "Username or id is required"
8888
assert not (args.username is not None and args.id is not None), "Cannot specify both username and id"
8989
if args.username is not None:
9090
assert args.id is None
91-
user = await user_pool.getUserByUsername(args.username)
91+
user = await user_pool.get_user_by_username(args.username)
9292
else:
9393
assert args.id is not None
9494
assert args.username is None
95-
user = await user_pool.getUserById(args.id)
95+
user = await user_pool.get_user_by_id(args.id)
9696
if user is None:
9797
print(f"Error: User does not exist")
9898
return
9999
if not args.yes:
100-
if input(f"Are you sure you want to delete user **{await user.toString()}**, "
100+
if input(f"Are you sure you want to delete user **{await user.to_string()}**, "
101101
"together with all data associated? (y/[n])").lower() != "y":
102102
print("Cancelled.")
103103
return
104-
await db_pool.deleteDatabasePermanently(user.id)
105-
await user_pool.deleteUserPermanently(user.id)
104+
await db_pool.delete_database_permanently(user.id)
105+
await user_pool.delete_user_permanently(user.id)
106106
print("User deleted.")
107107

108108
elif args.subparser == "list":
@@ -116,7 +116,7 @@ def parseStorage(s: str) -> int:
116116
def formatascii(s):
117117
return s.encode('ascii', 'replace').decode()
118118
if args.table:
119-
tablePrint(
119+
table_print(
120120
["ID", "Username", "Name", "Admin", "Mandatory Tags", "Max Storage", "Last Active"],
121121
[[
122122
(user_info:=(await user.info()))["id"],
@@ -125,12 +125,12 @@ def formatascii(s):
125125
'X' if user_info["is_admin"] else ' ',
126126
'; '.join(user_info["mandatory_tags"]),
127127
f"{(user_info['max_storage'])/1024/1024:.1f} MB",
128-
TimeUtils.stamp2Local(user_info["last_active"]).strftime("%Y-%m-%d %H:%M:%S")
128+
TimeUtils.stamp2local(user_info["last_active"]).strftime("%Y-%m-%d %H:%M:%S")
129129
] for user in all_users]
130130
)
131131
else:
132132
for user in all_users:
133-
print(await user.toString())
133+
print(await user.to_string())
134134

135135
else:
136136
parser.print_usage()

lires/core/bibReader.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -9,9 +9,9 @@
99
import pybtex.scanner
1010
from pylatexenc import latex2text
1111
import multiprocessing as mp
12-
from ..utils import randomAlphaNumeric
12+
from ..utils import random_alphanumeric
1313

14-
async def checkBibtexValidity(
14+
async def check_bibtex_validity(
1515
bib_str: str,
1616
onerror: Optional[Callable[[str], Awaitable[None]]] = None
1717
) -> bool:
@@ -45,7 +45,7 @@ def __init__(self, mode = "single"):
4545
self.mode = mode
4646

4747
@classmethod
48-
def removeAbstract(cls, bib_str: str) -> str:
48+
def remove_abstract(cls, bib_str: str) -> str:
4949
"""
5050
Remove abstract from bib string
5151
"""
@@ -56,7 +56,7 @@ def removeAbstract(cls, bib_str: str) -> str:
5656
return bib_data.to_string("bibtex")
5757

5858
@classmethod
59-
def formatBib(cls, bib_str: str) -> str:
59+
def format(cls, bib_str: str) -> str:
6060
""" Format bib string """
6161
bib_data = pybtex.database.parse_string(bib_str, bib_format="bibtex")
6262
return bib_data.to_string("bibtex")
@@ -114,7 +114,7 @@ class ParsedRef(TypedDict):
114114
year: str
115115
authors: list[str]
116116
publication: str
117-
async def parseBibtex(bib_single: str) -> ParsedRef:
117+
async def parse_bibtex(bib_single: str) -> ParsedRef:
118118
"""
119119
parse bibtex and extract useful entries
120120
"""
@@ -147,7 +147,7 @@ async def parseBibtex(bib_single: str) -> ParsedRef:
147147

148148
class BibConverter(LiresBase):
149149
logger = LiresBase.loggers().core
150-
async def fromNBib(self, nb: str) -> str:
150+
async def from_nbib(self, nb: str) -> str:
151151
parsed = nbib.read(nb.strip("\n") + "\n")
152152
if not parsed:
153153
await self.logger.error("Error while parsing nbib")
@@ -187,11 +187,11 @@ async def fromNBib(self, nb: str) -> str:
187187
data.append((k, v))
188188

189189
bib_data = BibliographyData({
190-
f"{data_dict['year']}_{randomAlphaNumeric(5)}":
190+
f"{data_dict['year']}_{random_alphanumeric(5)}":
191191
Entry(doc_type, data)
192192
})
193193
return bib_data.to_string("bibtex")
194194

195-
def fromEndNote(self, en: str):
195+
def from_endnote(self, en: str):
196196
parser = refparser.EndnoteParser()
197197
return parser.toBibtex(en)

lires/core/dataClass.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -284,29 +284,29 @@ async def get(self, uuid: str) -> DataPoint:
284284
async def gets(self, uuids: list[str], sort_by='time_import', reverse = True) -> list[DataPoint]:
285285
""" Get DataPoints by uuids """
286286
conn = self.conn
287-
all_info = await conn.getMany(uuids, sort_by=sort_by, reverse=reverse)
287+
all_info = await conn.get_many(uuids, sort_by=sort_by, reverse=reverse)
288288
tasks = [assembleDatapoint(info, self) for info in all_info]
289289
return await asyncio.gather(*tasks)
290290

291291
async def getAll(self, sort_by = 'time_import', reverse=True) -> list[DataPoint]:
292292
""" Get all DataPoints, may remove in the future """
293-
all_info = await self.conn.getAll(sort_by=sort_by, reverse=reverse)
293+
all_info = await self.conn.get_all(sort_by=sort_by, reverse=reverse)
294294
return await asyncio.gather(*[assembleDatapoint(info, self) for info in all_info])
295295

296296
async def getIDByTags(self, tags: Union[list, set, DataTags], from_uids: Optional[List[str]] = None) -> list[str]:
297297
"""
298298
Get DataPoints by tags, including all child tags
299299
"""
300300
async def _getByStrictIntersect(tags: DataTags, from_uids: Optional[List[str]] = None) -> list[str]:
301-
return await self.conn.filter(from_uids=from_uids, tags=tags.toOrderedList(), strict=True, ignore_case=False)
301+
return await self.conn.filter(from_uids=from_uids, tags=tags.to_ordered_list(), strict=True, ignore_case=False)
302302
async def _getBySingle(tag: str, from_uids: Optional[List[str]] = None) -> list[str]:
303303
return await self.conn.filter(from_uids=from_uids, tags=[tag], strict=True, ignore_case=False)
304304

305305
all_tags = DataTags(await self.conn.tags())
306306
strict_query_tags = DataTags() # the exact tags to be queried
307307
relaxed_query_tag_groups: list[DataTags] = [] # the tags groups that will be relaxed by union of each group
308308
for t in tags:
309-
if len(_w_child_t:= DataTags([t]).withChildsFrom(all_tags))==1:
309+
if len(_w_child_t:= DataTags([t]).with_childs_from(all_tags))==1:
310310
strict_query_tags.add(_w_child_t.pop())
311311
else:
312312
relaxed_query_tag_groups.append(_w_child_t)
@@ -338,7 +338,7 @@ async def renameTag(self, tag_old: str, tag_new: str) -> bool:
338338
for d in data:
339339
d: DataPoint
340340
t = d.tags
341-
t = TagRule.renameTag(t, tag_old, tag_new)
341+
t = TagRule.rename_tag(t, tag_old, tag_new)
342342
if t is not None:
343343
tasks.append(d.fm.writeTags(t))
344344
await asyncio.gather(*tasks)
@@ -355,7 +355,7 @@ async def deleteTag(self, tag: str) -> bool:
355355
for d in data:
356356
d: DataPoint
357357
ori_tags = d.tags
358-
after_deleted = TagRule.deleteTag(ori_tags, tag)
358+
after_deleted = TagRule.delete_tag(ori_tags, tag)
359359
if after_deleted is not None:
360360
tasks.append(d.fm.writeTags(after_deleted))
361361
await asyncio.gather(*tasks)

0 commit comments

Comments
 (0)