hh-applicant-tool 0.7.10__py3-none-any.whl → 1.4.7__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (75) hide show
  1. hh_applicant_tool/__init__.py +1 -0
  2. hh_applicant_tool/__main__.py +1 -1
  3. hh_applicant_tool/ai/base.py +2 -0
  4. hh_applicant_tool/ai/openai.py +23 -33
  5. hh_applicant_tool/api/client.py +50 -64
  6. hh_applicant_tool/api/errors.py +51 -7
  7. hh_applicant_tool/constants.py +0 -3
  8. hh_applicant_tool/datatypes.py +291 -0
  9. hh_applicant_tool/main.py +233 -111
  10. hh_applicant_tool/operations/apply_similar.py +266 -362
  11. hh_applicant_tool/operations/authorize.py +256 -120
  12. hh_applicant_tool/operations/call_api.py +18 -8
  13. hh_applicant_tool/operations/check_negotiations.py +102 -0
  14. hh_applicant_tool/operations/check_proxy.py +30 -0
  15. hh_applicant_tool/operations/config.py +119 -16
  16. hh_applicant_tool/operations/install.py +34 -0
  17. hh_applicant_tool/operations/list_resumes.py +24 -10
  18. hh_applicant_tool/operations/log.py +77 -0
  19. hh_applicant_tool/operations/migrate_db.py +65 -0
  20. hh_applicant_tool/operations/query.py +120 -0
  21. hh_applicant_tool/operations/refresh_token.py +14 -13
  22. hh_applicant_tool/operations/reply_employers.py +148 -167
  23. hh_applicant_tool/operations/settings.py +95 -0
  24. hh_applicant_tool/operations/uninstall.py +26 -0
  25. hh_applicant_tool/operations/update_resumes.py +21 -10
  26. hh_applicant_tool/operations/whoami.py +40 -7
  27. hh_applicant_tool/storage/__init__.py +4 -0
  28. hh_applicant_tool/storage/facade.py +24 -0
  29. hh_applicant_tool/storage/models/__init__.py +0 -0
  30. hh_applicant_tool/storage/models/base.py +169 -0
  31. hh_applicant_tool/storage/models/contact.py +16 -0
  32. hh_applicant_tool/storage/models/employer.py +12 -0
  33. hh_applicant_tool/storage/models/negotiation.py +16 -0
  34. hh_applicant_tool/storage/models/resume.py +19 -0
  35. hh_applicant_tool/storage/models/setting.py +6 -0
  36. hh_applicant_tool/storage/models/vacancy.py +36 -0
  37. hh_applicant_tool/storage/queries/migrations/.gitkeep +0 -0
  38. hh_applicant_tool/storage/queries/schema.sql +119 -0
  39. hh_applicant_tool/storage/repositories/__init__.py +0 -0
  40. hh_applicant_tool/storage/repositories/base.py +176 -0
  41. hh_applicant_tool/storage/repositories/contacts.py +19 -0
  42. hh_applicant_tool/storage/repositories/employers.py +13 -0
  43. hh_applicant_tool/storage/repositories/negotiations.py +12 -0
  44. hh_applicant_tool/storage/repositories/resumes.py +14 -0
  45. hh_applicant_tool/storage/repositories/settings.py +34 -0
  46. hh_applicant_tool/storage/repositories/vacancies.py +8 -0
  47. hh_applicant_tool/storage/utils.py +49 -0
  48. hh_applicant_tool/utils/__init__.py +31 -0
  49. hh_applicant_tool/utils/attrdict.py +6 -0
  50. hh_applicant_tool/utils/binpack.py +167 -0
  51. hh_applicant_tool/utils/config.py +55 -0
  52. hh_applicant_tool/utils/dateutil.py +19 -0
  53. hh_applicant_tool/{jsonc.py → utils/jsonc.py} +12 -6
  54. hh_applicant_tool/utils/jsonutil.py +61 -0
  55. hh_applicant_tool/utils/log.py +144 -0
  56. hh_applicant_tool/utils/misc.py +12 -0
  57. hh_applicant_tool/utils/mixins.py +220 -0
  58. hh_applicant_tool/utils/string.py +27 -0
  59. hh_applicant_tool/utils/terminal.py +19 -0
  60. hh_applicant_tool/utils/user_agent.py +17 -0
  61. hh_applicant_tool-1.4.7.dist-info/METADATA +628 -0
  62. hh_applicant_tool-1.4.7.dist-info/RECORD +67 -0
  63. hh_applicant_tool/ai/blackbox.py +0 -55
  64. hh_applicant_tool/color_log.py +0 -47
  65. hh_applicant_tool/mixins.py +0 -13
  66. hh_applicant_tool/operations/clear_negotiations.py +0 -109
  67. hh_applicant_tool/operations/delete_telemetry.py +0 -30
  68. hh_applicant_tool/operations/get_employer_contacts.py +0 -348
  69. hh_applicant_tool/telemetry_client.py +0 -106
  70. hh_applicant_tool/types.py +0 -45
  71. hh_applicant_tool/utils.py +0 -119
  72. hh_applicant_tool-0.7.10.dist-info/METADATA +0 -452
  73. hh_applicant_tool-0.7.10.dist-info/RECORD +0 -33
  74. {hh_applicant_tool-0.7.10.dist-info → hh_applicant_tool-1.4.7.dist-info}/WHEEL +0 -0
  75. {hh_applicant_tool-0.7.10.dist-info → hh_applicant_tool-1.4.7.dist-info}/entry_points.txt +0 -0
@@ -1,49 +1,152 @@
1
+ from __future__ import annotations
2
+
1
3
  import argparse
4
+ import json
2
5
  import logging
3
6
  import os
7
+ import platform
4
8
  import subprocess
5
- from typing import Any
9
+ from typing import TYPE_CHECKING, Any
6
10
 
7
- from ..main import BaseOperation
8
- from ..main import Namespace as BaseNamespace
11
+ from ..main import BaseNamespace, BaseOperation
9
12
 
10
- logger = logging.getLogger(__package__)
13
+ if TYPE_CHECKING:
14
+ from ..main import HHApplicantTool
11
15
 
12
- EDITOR = os.getenv("EDITOR", "nano")
16
+
17
+ logger = logging.getLogger(__package__)
13
18
 
14
19
 
15
20
  class Namespace(BaseNamespace):
16
21
  show_path: bool
17
22
  key: str
23
+ set: list[str]
24
+ edit: bool
25
+ unset: str
18
26
 
19
27
 
20
28
  def get_value(data: dict[str, Any], path: str) -> Any:
21
29
  for key in path.split("."):
22
- if key not in data:
30
+ if isinstance(data, dict):
31
+ data = data.get(key)
32
+ else:
23
33
  return None
24
- data = data[key]
25
34
  return data
26
35
 
27
36
 
37
+ def set_value(data: dict[str, Any], path: str, value: Any) -> None:
38
+ """Устанавливает значение во вложенном словаре по ключу в виде строки."""
39
+ keys = path.split(".")
40
+ for key in keys[:-1]:
41
+ data = data.setdefault(key, {})
42
+ data[keys[-1]] = value
43
+
44
+
45
+ def del_value(data: dict[str, Any], path: str) -> None:
46
+ """Удаляет значение из вложенного словаря по ключу в виде строки."""
47
+ keys = path.split(".")
48
+ for key in keys[:-1]:
49
+ if not isinstance(data, dict) or key not in data:
50
+ return False
51
+ data = data[key]
52
+
53
+ try:
54
+ del data[keys[-1]]
55
+ return True
56
+ except KeyError:
57
+ return False
58
+
59
+
60
+ def parse_scalar(value: str) -> bool | int | float | str:
61
+ if value == "null":
62
+ return None
63
+ if value in ["true", "false"]:
64
+ return "t" in value
65
+ try:
66
+ return float(value) if "." in value else int(value)
67
+ except ValueError:
68
+ return value
69
+
70
+
28
71
  class Operation(BaseOperation):
29
- """Операции с конфигурационным файлом"""
72
+ """
73
+ Операции с конфигурационным файлом.
74
+ По умолчанию выводит содержимое конфига.
75
+ """
30
76
 
31
77
  def setup_parser(self, parser: argparse.ArgumentParser) -> None:
32
- parser.add_argument(
78
+ group = parser.add_mutually_exclusive_group()
79
+ group.add_argument(
80
+ "-e",
81
+ "--edit",
82
+ action="store_true",
83
+ help="Открыть конфигурационный файл в редакторе",
84
+ )
85
+ group.add_argument(
86
+ "-k", "--key", help="Вывести отдельное значение из конфига"
87
+ )
88
+ group.add_argument(
89
+ "-s",
90
+ "--set",
91
+ nargs=2,
92
+ metavar=("KEY", "VALUE"),
93
+ help="Установить значение в конфиг, например, --set openai.model gpt-4o",
94
+ )
95
+ group.add_argument(
96
+ "-u", "--unset", metavar="KEY", help="Удалить ключ из конфига"
97
+ )
98
+ group.add_argument(
33
99
  "-p",
34
100
  "--show-path",
35
101
  "--path",
36
- action=argparse.BooleanOptionalAction,
102
+ action="store_true",
37
103
  help="Вывести полный путь к конфигу",
38
104
  )
39
- parser.add_argument("-k", "--key", help="Вывести отдельное значение из конфига")
40
105
 
41
- def run(self, args: Namespace, *_) -> None:
106
+ def run(self, applicant_tool: HHApplicantTool) -> None:
107
+ args = applicant_tool.args
108
+ config = applicant_tool.config
109
+ if args.set:
110
+ key, value = args.set
111
+ set_value(config, key, parse_scalar(value))
112
+ config.save()
113
+ logger.info("Значение '%s' для ключа '%s' сохранено.", value, key)
114
+ return
115
+
116
+ if args.unset:
117
+ key = args.unset
118
+ if del_value(config, key):
119
+ config.save()
120
+ logger.info("Ключ '%s' удален из конфига.", key)
121
+ else:
122
+ logger.warning("Ключ '%s' не найден в конфиге.", key)
123
+ return
124
+
42
125
  if args.key:
43
- print(get_value(args.config, args.key))
126
+ value = get_value(config, args.key)
127
+ if value is not None:
128
+ print(value)
44
129
  return
45
- config_path = str(args.config._config_path)
130
+
131
+ config_path = str(config._config_path)
46
132
  if args.show_path:
47
133
  print(config_path)
48
- else:
49
- subprocess.call([EDITOR, config_path])
134
+ return
135
+
136
+ if args.edit:
137
+ self._open_editor(config_path)
138
+ return
139
+
140
+ # Default action: show content
141
+ print(json.dumps(config, indent=2, ensure_ascii=False))
142
+
143
+ def _open_editor(self, filepath: str) -> None:
144
+ """Открывает файл в редакторе по умолчанию в зависимости от ОС."""
145
+ match platform.system():
146
+ case "Windows":
147
+ os.startfile(filepath)
148
+ case "Darwin": # macOS
149
+ subprocess.run(["open", filepath], check=True)
150
+ case _: # Linux и остальные (аналог else)
151
+ editor = os.getenv("EDITOR", "xdg-open")
152
+ subprocess.run([editor, filepath], check=True)
@@ -0,0 +1,34 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import logging
5
+ import sys
6
+ from runpy import run_module
7
+ from typing import TYPE_CHECKING
8
+
9
+ from ..main import BaseNamespace, BaseOperation
10
+
11
+ if TYPE_CHECKING:
12
+ from ..main import HHApplicantTool
13
+
14
+
15
+ logger = logging.getLogger(__package__)
16
+
17
+
18
+ class Namespace(BaseNamespace):
19
+ pass
20
+
21
+
22
+ class Operation(BaseOperation):
23
+ """Установит Chromium и другие зависимости"""
24
+
25
+ def setup_parser(self, parser: argparse.ArgumentParser) -> None:
26
+ pass
27
+
28
+ def run(self, applicant_tool: HHApplicantTool) -> None:
29
+ orig_argv = sys.argv
30
+ sys.argv = ["playwright", "install", "chromium"]
31
+ try:
32
+ run_module("playwright", run_name="__main__")
33
+ finally:
34
+ sys.argv = orig_argv
@@ -1,14 +1,19 @@
1
- # Этот модуль можно использовать как образец для других
1
+ from __future__ import annotations
2
+
2
3
  import argparse
3
4
  import logging
5
+ from typing import TYPE_CHECKING
4
6
 
5
7
  from prettytable import PrettyTable
6
8
 
7
- from ..api import ApiClient
8
- from ..main import BaseOperation
9
- from ..main import Namespace as BaseNamespace
10
- from ..types import ApiListResponse
11
- from ..utils import truncate_string
9
+ from ..datatypes import PaginatedItems
10
+ from ..main import BaseNamespace, BaseOperation
11
+ from ..utils.string import shorten
12
+
13
+ if TYPE_CHECKING:
14
+ from .. import datatypes
15
+ from ..main import HHApplicantTool
16
+
12
17
 
13
18
  logger = logging.getLogger(__package__)
14
19
 
@@ -20,20 +25,29 @@ class Namespace(BaseNamespace):
20
25
  class Operation(BaseOperation):
21
26
  """Список резюме"""
22
27
 
28
+ __aliases__ = ("ls-resumes", "resumes")
29
+
23
30
  def setup_parser(self, parser: argparse.ArgumentParser) -> None:
24
31
  pass
25
32
 
26
- def run(self, args: Namespace, api_client: ApiClient, *_) -> None:
27
- resumes: ApiListResponse = api_client.get("/resumes/mine")
28
- t = PrettyTable(field_names=["ID", "Название", "Статус"], align="l", valign="t")
33
+ def run(self, tool: HHApplicantTool) -> None:
34
+ resumes: PaginatedItems[datatypes.Resume] = tool.get_resumes()
35
+ storage = tool.storage
36
+ for resume in resumes["items"]:
37
+ storage.resumes.save(resume)
38
+
39
+ t = PrettyTable(
40
+ field_names=["ID", "Название", "Статус"], align="l", valign="t"
41
+ )
29
42
  t.add_rows(
30
43
  [
31
44
  (
32
45
  x["id"],
33
- truncate_string(x["title"]),
46
+ shorten(x["title"]),
34
47
  x["status"]["name"].title(),
35
48
  )
36
49
  for x in resumes["items"]
37
50
  ]
38
51
  )
39
52
  print(t)
53
+ print(f"\nНайдено резюме: {resumes['found']}")
@@ -0,0 +1,77 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import logging
5
+ import os
6
+ import shutil
7
+ import subprocess
8
+ import sys
9
+ from typing import TYPE_CHECKING
10
+
11
+ from ..main import BaseNamespace, BaseOperation
12
+
13
+ if TYPE_CHECKING:
14
+ from ..main import HHApplicantTool
15
+
16
+
17
+ logger = logging.getLogger(__package__)
18
+
19
+
20
+ class Namespace(BaseNamespace):
21
+ follow: bool
22
+
23
+
24
+ class Operation(BaseOperation):
25
+ """Просмотр файла-лога"""
26
+
27
+ def setup_parser(self, parser: argparse.ArgumentParser) -> None:
28
+ # Изменено на -F для соответствия стандарту less/tail
29
+ parser.add_argument(
30
+ "-f",
31
+ "--follow",
32
+ action="store_true",
33
+ help="Следить за файлом (режим follow, аналог less +F)",
34
+ )
35
+
36
+ def run(self, tool: HHApplicantTool) -> None:
37
+ log_path = tool.log_file
38
+
39
+ if not os.path.exists(log_path):
40
+ logger.error("Файл лога не найден: %s", log_path)
41
+ return 1
42
+
43
+ if sys.platform == "win32":
44
+ os.startfile(log_path)
45
+ return
46
+
47
+ pager = os.getenv("PAGER", "less")
48
+ if not shutil.which(pager):
49
+ logger.error("Не найден просмотрщик '%s'", pager)
50
+ if pager == "less":
51
+ logger.error(
52
+ 'Попробуйте установить less: "sudo apt install less" или "sudo yum install less"'
53
+ )
54
+ return 1
55
+
56
+ cmd = [pager]
57
+
58
+ if pager == "less":
59
+ # -R позволяет отображать цвета (ANSI codes)
60
+ # -S отключает перенос строк (удобно для логов)
61
+ cmd.extend(["-R", "-S"])
62
+ if tool.args.follow:
63
+ # В less режим слежения включается через команду +F
64
+ cmd.append("+F")
65
+
66
+ cmd.append(str(log_path))
67
+
68
+ try:
69
+ # Запускаем процесс. check=False, так как выход из pager
70
+ # по Ctrl+C может вернуть ненулевой код.
71
+ subprocess.run(cmd, check=False)
72
+ except FileNotFoundError:
73
+ logger.error("Не удалось запустить просмотрщик '%s'", pager)
74
+ return 1
75
+ except KeyboardInterrupt:
76
+ # Обработка прерывания, чтобы не выводить traceback в консоль
77
+ pass
@@ -0,0 +1,65 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import logging
5
+ import os
6
+ import sqlite3
7
+ import sys
8
+ from typing import TYPE_CHECKING
9
+
10
+ from ..main import BaseNamespace, BaseOperation
11
+ from ..storage import apply_migration, list_migrations
12
+
13
+ if TYPE_CHECKING:
14
+ from ..main import HHApplicantTool
15
+
16
+ SUCKASS = "✅ Success!"
17
+
18
+ logger = logging.getLogger(__package__)
19
+
20
+
21
+ class Namespace(BaseNamespace):
22
+ pass
23
+
24
+
25
+ class Operation(BaseOperation):
26
+ """Выполняет миграцию БД. Если первым аргументом имя миграции не передано, выведет их список.""" # noqa: E501
27
+
28
+ __aliases__: list[str] = ["migrate"]
29
+
30
+ def setup_parser(self, parser: argparse.ArgumentParser) -> None:
31
+ parser.add_argument("name", nargs="?", help="Имя миграции")
32
+
33
+ def run(self, tool: HHApplicantTool) -> None:
34
+ def apply(name: str) -> None:
35
+ apply_migration(tool.db, name)
36
+ print(SUCKASS)
37
+
38
+ try:
39
+ if a := tool.args.name:
40
+ return apply(a)
41
+ if not (migrations := list_migrations()):
42
+ return
43
+ if not sys.stdout.isatty():
44
+ print(*list_migrations(), sep=os.sep)
45
+ return
46
+ print("List of migrations:")
47
+ print()
48
+ for n, migration in enumerate(migrations, 1):
49
+ print(f" [{n}]: {migration}")
50
+ print()
51
+ L = len(migrations)
52
+ if n := int(
53
+ input(
54
+ f"Choose migration [1{f'-{L}' if L > 1 else ''}] (Keep empty to exit): " # noqa: E501
55
+ )
56
+ or 0
57
+ ):
58
+ apply(migrations[n - 1])
59
+ except sqlite3.OperationalError as ex:
60
+ logger.exception(ex)
61
+ logger.warning(
62
+ f"Если ничего не помогает, то вы можете просто удалить базу, сделав бекап:\n\n"
63
+ f" $ mv {tool.db_path}{{,.bak}}"
64
+ )
65
+ return 1
@@ -0,0 +1,120 @@
1
+ from __future__ import annotations
2
+
3
+ import argparse
4
+ import csv
5
+ import logging
6
+ import sqlite3
7
+ import sys
8
+ from typing import TYPE_CHECKING
9
+
10
+ from prettytable import PrettyTable
11
+
12
+ from ..main import BaseNamespace, BaseOperation
13
+
14
+ if TYPE_CHECKING:
15
+ from ..main import HHApplicantTool
16
+
17
+ try:
18
+ import readline
19
+
20
+ readline.parse_and_bind("tab: complete")
21
+ except ImportError:
22
+ readline = None
23
+
24
+ MAX_RESULTS = 10
25
+
26
+
27
+ logger = logging.getLogger(__package__)
28
+
29
+
30
+ class Namespace(BaseNamespace):
31
+ pass
32
+
33
+
34
+ class Operation(BaseOperation):
35
+ """Выполняет SQL-запрос. Поддерживает вывод в консоль или CSV файл."""
36
+
37
+ __aliases__: list[str] = ["sql"]
38
+
39
+ def setup_parser(self, parser: argparse.ArgumentParser) -> None:
40
+ parser.add_argument("sql", nargs="?", help="SQL запрос")
41
+ parser.add_argument(
42
+ "--csv", action="store_true", help="Вывести результат в формате CSV"
43
+ )
44
+ parser.add_argument(
45
+ "-o",
46
+ "--output",
47
+ type=argparse.FileType("w", encoding="utf-8"),
48
+ help="Файл для сохранения",
49
+ )
50
+
51
+ def run(self, tool: HHApplicantTool) -> None:
52
+ def execute(sql_query: str) -> None:
53
+ sql_query = sql_query.strip()
54
+ if not sql_query:
55
+ return
56
+ try:
57
+ cursor = tool.db.cursor()
58
+ cursor.execute(sql_query)
59
+
60
+ if cursor.description:
61
+ columns = [d[0] for d in cursor.description]
62
+
63
+ if tool.args.csv or tool.args.output:
64
+ # Если -o не задан, используем sys.stdout
65
+ output = tool.args.output or sys.stdout
66
+ writer = csv.writer(output)
67
+ writer.writerow(columns)
68
+ writer.writerows(cursor.fetchall())
69
+
70
+ if tool.args.output:
71
+ print(f"✅ Exported to {tool.args.output.name}")
72
+ return
73
+
74
+ rows = cursor.fetchmany(MAX_RESULTS + 1)
75
+ if not rows:
76
+ print("No results found.")
77
+ return
78
+
79
+ table = PrettyTable()
80
+ table.field_names = columns
81
+ for row in rows[:MAX_RESULTS]:
82
+ table.add_row(row)
83
+
84
+ print(table)
85
+ if len(rows) > MAX_RESULTS:
86
+ print(
87
+ f"⚠️ Warning: Showing only first {MAX_RESULTS} results."
88
+ )
89
+ else:
90
+ tool.db.commit()
91
+ print(f"OK. Rows affected: {cursor.rowcount}")
92
+
93
+ except sqlite3.Error as ex:
94
+ print(f"❌ SQL Error: {ex}")
95
+ return 1
96
+
97
+ if initial_sql := tool.args.sql:
98
+ return execute(initial_sql)
99
+
100
+ if not sys.stdin.isatty():
101
+ return execute(sys.stdin.read())
102
+
103
+ print("SQL Console (q or ^D to exit)")
104
+ try:
105
+ while True:
106
+ try:
107
+ user_input = input("query> ").strip()
108
+ if user_input.lower() in (
109
+ "exit",
110
+ "quit",
111
+ "q",
112
+ ):
113
+ break
114
+ execute(user_input)
115
+ print()
116
+ except KeyboardInterrupt:
117
+ print("^C")
118
+ continue
119
+ except EOFError:
120
+ print()
@@ -1,11 +1,14 @@
1
- # Этот модуль можно использовать как образец для других
1
+ from __future__ import annotations
2
+
2
3
  import argparse
3
4
  import logging
4
- from typing import Any
5
- from ..api import ApiError, ApiClient
6
- from ..main import BaseOperation
7
- from ..main import Namespace as BaseNamespace
8
- from ..utils import print_err
5
+ from typing import TYPE_CHECKING
6
+
7
+ from ..main import BaseNamespace, BaseOperation
8
+
9
+ if TYPE_CHECKING:
10
+ from ..main import HHApplicantTool
11
+
9
12
 
10
13
  logger = logging.getLogger(__package__)
11
14
 
@@ -17,13 +20,11 @@ class Namespace(BaseNamespace):
17
20
  class Operation(BaseOperation):
18
21
  """Получает новый access_token."""
19
22
 
23
+ __aliases__ = ["refresh"]
24
+
20
25
  def setup_parser(self, parser: argparse.ArgumentParser) -> None:
21
26
  pass
22
27
 
23
- def run(self, _, api_client: ApiClient, *args: Any) -> None:
24
- try:
25
- api_client.refresh_access_token()
26
- print("✅ Токен обновлен!")
27
- except ApiError as ex:
28
- print_err("❗ Ошибка:", ex)
29
- return 1
28
+ def run(self, tool: HHApplicantTool) -> None:
29
+ tool.api_client.refresh_access_token()
30
+ print("✅ Токен обновлен!")