eranmi commited on
Commit
a3619f1
·
1 Parent(s): cf2b318

CI+refactoring according to mypy and pylint

Browse files
.github/workflows/ci.yml ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: CI
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ lint:
11
+ runs-on: ubuntu-latest
12
+
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+
16
+ - name: Set up Python
17
+ uses: actions/setup-python@v5
18
+ with:
19
+ python-version: "3.10"
20
+
21
+ - name: Install Poetry
22
+ uses: abatilo/actions-poetry@v2
23
+ with:
24
+ poetry-version: "2.1.1"
25
+
26
+ - name: Verify Poetry Installation
27
+ run: poetry --version
28
+
29
+ - name: Install dependencies
30
+ run: poetry install --with dev
31
+
32
+ - name: Run Black
33
+ run: poetry run black --check .
34
+
35
+ - name: Run Mypy
36
+ run: poetry run mypy .
37
+
38
+ - name: Run Pylint
39
+ run: |
40
+ poetry run pylint . | tee pylint-output.txt
41
+ score=$(tail -n 2 pylint-output.txt | grep -oP "rated at \K[0-9.]+")
42
+ echo "Pylint score: $score"
43
+ awk -v s="$score" 'BEGIN {exit (s >= 9.5) ? 0 : 1}'
.gitignore CHANGED
@@ -1,6 +1,7 @@
1
  # Custom Python .gitignore file
2
  .DS_Store
3
  activate_poetry.sh
 
4
  uploaded_docs/*
5
  output/*
6
 
 
1
  # Custom Python .gitignore file
2
  .DS_Store
3
  activate_poetry.sh
4
+ run_docker.sh
5
  uploaded_docs/*
6
  output/*
7
 
mypy.ini ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ # mypy.ini
2
+
3
+ [mypy]
4
+ ignore_missing_imports = True
5
+
poetry.lock CHANGED
@@ -200,6 +200,53 @@ charset-normalizer = ["charset-normalizer"]
200
  html5lib = ["html5lib"]
201
  lxml = ["lxml"]
202
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
203
  [[package]]
204
  name = "build"
205
  version = "1.2.2.post1"
@@ -447,7 +494,7 @@ version = "8.1.8"
447
  description = "Composable command line interface toolkit"
448
  optional = false
449
  python-versions = ">=3.7"
450
- groups = ["main"]
451
  files = [
452
  {file = "click-8.1.8-py3-none-any.whl", hash = "sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2"},
453
  {file = "click-8.1.8.tar.gz", hash = "sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a"},
@@ -467,7 +514,7 @@ files = [
467
  {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
468
  {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
469
  ]
470
- markers = {main = "os_name == \"nt\" or platform_system == \"Windows\" or sys_platform == \"win32\"", dev = "sys_platform == \"win32\""}
471
 
472
  [[package]]
473
  name = "coloredlogs"
@@ -565,7 +612,7 @@ version = "1.3.0"
565
  description = "Backport of PEP 654 (exception groups)"
566
  optional = false
567
  python-versions = ">=3.7"
568
- groups = ["main"]
569
  files = [
570
  {file = "exceptiongroup-1.3.0-py3-none-any.whl", hash = "sha256:4d111e6e0c13d0644cad6ddaa7ed0261a0b36971f6d23e7ec9b4b9097da78a10"},
571
  {file = "exceptiongroup-1.3.0.tar.gz", hash = "sha256:b241f5885f560bc56a59ee63ca4c6a8bfa46ae4ad651af316d4e81817bb9fd88"},
@@ -1203,6 +1250,18 @@ enabler = ["pytest-enabler (>=2.2)"]
1203
  test = ["jaraco.test (>=5.4)", "pytest (>=6,!=8.1.*)", "zipp (>=3.17)"]
1204
  type = ["pytest-mypy"]
1205
 
 
 
 
 
 
 
 
 
 
 
 
 
1206
  [[package]]
1207
  name = "isort"
1208
  version = "6.0.1"
@@ -1578,6 +1637,73 @@ docs = ["sphinx"]
1578
  gmpy = ["gmpy2 (>=2.1.0a4) ; platform_python_implementation != \"PyPy\""]
1579
  tests = ["pytest (>=4.6)"]
1580
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1581
  [[package]]
1582
  name = "numpy"
1583
  version = "2.2.5"
@@ -1966,7 +2092,7 @@ version = "24.2"
1966
  description = "Core utilities for Python packages"
1967
  optional = false
1968
  python-versions = ">=3.8"
1969
- groups = ["main"]
1970
  files = [
1971
  {file = "packaging-24.2-py3-none-any.whl", hash = "sha256:09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759"},
1972
  {file = "packaging-24.2.tar.gz", hash = "sha256:c228a6dc5e932d346bc5739379109d49e8853dd8223571c7c5b55260edc0b97f"},
@@ -2055,6 +2181,18 @@ sql-other = ["SQLAlchemy (>=2.0.0)", "adbc-driver-postgresql (>=0.8.0)", "adbc-d
2055
  test = ["hypothesis (>=6.46.1)", "pytest (>=7.3.2)", "pytest-xdist (>=2.2.0)"]
2056
  xml = ["lxml (>=4.9.2)"]
2057
 
 
 
 
 
 
 
 
 
 
 
 
 
2058
  [[package]]
2059
  name = "pillow"
2060
  version = "11.2.1"
@@ -2172,6 +2310,22 @@ docs = ["furo (>=2024.8.6)", "proselint (>=0.14)", "sphinx (>=8.1.3)", "sphinx-a
2172
  test = ["appdirs (==1.4.4)", "covdefaults (>=2.3)", "pytest (>=8.3.4)", "pytest-cov (>=6)", "pytest-mock (>=3.14)"]
2173
  type = ["mypy (>=1.14.1)"]
2174
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2175
  [[package]]
2176
  name = "posthog"
2177
  version = "4.0.0"
@@ -2416,7 +2570,7 @@ version = "2.19.1"
2416
  description = "Pygments is a syntax highlighting package written in Python."
2417
  optional = false
2418
  python-versions = ">=3.8"
2419
- groups = ["main"]
2420
  files = [
2421
  {file = "pygments-2.19.1-py3-none-any.whl", hash = "sha256:9ea1544ad55cecf4b8242fab6dd35a93bbce657034b0611ee383099054ab6d8c"},
2422
  {file = "pygments-2.19.1.tar.gz", hash = "sha256:61c16d2a8576dc0649d9f39e089b5f02bcd27fba10d8fb4dcc28173f7a45151f"},
@@ -2523,6 +2677,30 @@ files = [
2523
  [package.extras]
2524
  dev = ["build", "flake8", "mypy", "pytest", "twine"]
2525
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2526
  [[package]]
2527
  name = "python-dateutil"
2528
  version = "2.9.0.post0"
@@ -3607,4 +3785,4 @@ type = ["pytest-mypy"]
3607
  [metadata]
3608
  lock-version = "2.1"
3609
  python-versions = ">=3.10,<3.11"
3610
- content-hash = "2bf0903eb5a87da022e3ba0fc805c42e1b32a7bf60600329bc788ef72651af70"
 
200
  html5lib = ["html5lib"]
201
  lxml = ["lxml"]
202
 
203
+ [[package]]
204
+ name = "black"
205
+ version = "25.1.0"
206
+ description = "The uncompromising code formatter."
207
+ optional = false
208
+ python-versions = ">=3.9"
209
+ groups = ["dev"]
210
+ files = [
211
+ {file = "black-25.1.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:759e7ec1e050a15f89b770cefbf91ebee8917aac5c20483bc2d80a6c3a04df32"},
212
+ {file = "black-25.1.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:0e519ecf93120f34243e6b0054db49c00a35f84f195d5bce7e9f5cfc578fc2da"},
213
+ {file = "black-25.1.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:055e59b198df7ac0b7efca5ad7ff2516bca343276c466be72eb04a3bcc1f82d7"},
214
+ {file = "black-25.1.0-cp310-cp310-win_amd64.whl", hash = "sha256:db8ea9917d6f8fc62abd90d944920d95e73c83a5ee3383493e35d271aca872e9"},
215
+ {file = "black-25.1.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:a39337598244de4bae26475f77dda852ea00a93bd4c728e09eacd827ec929df0"},
216
+ {file = "black-25.1.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:96c1c7cd856bba8e20094e36e0f948718dc688dba4a9d78c3adde52b9e6c2299"},
217
+ {file = "black-25.1.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:bce2e264d59c91e52d8000d507eb20a9aca4a778731a08cfff7e5ac4a4bb7096"},
218
+ {file = "black-25.1.0-cp311-cp311-win_amd64.whl", hash = "sha256:172b1dbff09f86ce6f4eb8edf9dede08b1fce58ba194c87d7a4f1a5aa2f5b3c2"},
219
+ {file = "black-25.1.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:4b60580e829091e6f9238c848ea6750efed72140b91b048770b64e74fe04908b"},
220
+ {file = "black-25.1.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:1e2978f6df243b155ef5fa7e558a43037c3079093ed5d10fd84c43900f2d8ecc"},
221
+ {file = "black-25.1.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3b48735872ec535027d979e8dcb20bf4f70b5ac75a8ea99f127c106a7d7aba9f"},
222
+ {file = "black-25.1.0-cp312-cp312-win_amd64.whl", hash = "sha256:ea0213189960bda9cf99be5b8c8ce66bb054af5e9e861249cd23471bd7b0b3ba"},
223
+ {file = "black-25.1.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:8f0b18a02996a836cc9c9c78e5babec10930862827b1b724ddfe98ccf2f2fe4f"},
224
+ {file = "black-25.1.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:afebb7098bfbc70037a053b91ae8437c3857482d3a690fefc03e9ff7aa9a5fd3"},
225
+ {file = "black-25.1.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:030b9759066a4ee5e5aca28c3c77f9c64789cdd4de8ac1df642c40b708be6171"},
226
+ {file = "black-25.1.0-cp313-cp313-win_amd64.whl", hash = "sha256:a22f402b410566e2d1c950708c77ebf5ebd5d0d88a6a2e87c86d9fb48afa0d18"},
227
+ {file = "black-25.1.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:a1ee0a0c330f7b5130ce0caed9936a904793576ef4d2b98c40835d6a65afa6a0"},
228
+ {file = "black-25.1.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:f3df5f1bf91d36002b0a75389ca8663510cf0531cca8aa5c1ef695b46d98655f"},
229
+ {file = "black-25.1.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:d9e6827d563a2c820772b32ce8a42828dc6790f095f441beef18f96aa6f8294e"},
230
+ {file = "black-25.1.0-cp39-cp39-win_amd64.whl", hash = "sha256:bacabb307dca5ebaf9c118d2d2f6903da0d62c9faa82bd21a33eecc319559355"},
231
+ {file = "black-25.1.0-py3-none-any.whl", hash = "sha256:95e8176dae143ba9097f351d174fdaf0ccd29efb414b362ae3fd72bf0f710717"},
232
+ {file = "black-25.1.0.tar.gz", hash = "sha256:33496d5cd1222ad73391352b4ae8da15253c5de89b93a80b3e2c8d9a19ec2666"},
233
+ ]
234
+
235
+ [package.dependencies]
236
+ click = ">=8.0.0"
237
+ mypy-extensions = ">=0.4.3"
238
+ packaging = ">=22.0"
239
+ pathspec = ">=0.9.0"
240
+ platformdirs = ">=2"
241
+ tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""}
242
+ typing-extensions = {version = ">=4.0.1", markers = "python_version < \"3.11\""}
243
+
244
+ [package.extras]
245
+ colorama = ["colorama (>=0.4.3)"]
246
+ d = ["aiohttp (>=3.10)"]
247
+ jupyter = ["ipython (>=7.8.0)", "tokenize-rt (>=3.2.0)"]
248
+ uvloop = ["uvloop (>=0.15.2)"]
249
+
250
  [[package]]
251
  name = "build"
252
  version = "1.2.2.post1"
 
494
  description = "Composable command line interface toolkit"
495
  optional = false
496
  python-versions = ">=3.7"
497
+ groups = ["main", "dev"]
498
  files = [
499
  {file = "click-8.1.8-py3-none-any.whl", hash = "sha256:63c132bbbed01578a06712a2d1f497bb62d9c1c0d329b7903a866228027263b2"},
500
  {file = "click-8.1.8.tar.gz", hash = "sha256:ed53c9d8990d83c2a27deae68e4ee337473f6330c040a31d4225c9574d16096a"},
 
514
  {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"},
515
  {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"},
516
  ]
517
+ markers = {main = "os_name == \"nt\" or platform_system == \"Windows\" or sys_platform == \"win32\"", dev = "platform_system == \"Windows\" or sys_platform == \"win32\""}
518
 
519
  [[package]]
520
  name = "coloredlogs"
 
612
  description = "Backport of PEP 654 (exception groups)"
613
  optional = false
614
  python-versions = ">=3.7"
615
+ groups = ["main", "dev"]
616
  files = [
617
  {file = "exceptiongroup-1.3.0-py3-none-any.whl", hash = "sha256:4d111e6e0c13d0644cad6ddaa7ed0261a0b36971f6d23e7ec9b4b9097da78a10"},
618
  {file = "exceptiongroup-1.3.0.tar.gz", hash = "sha256:b241f5885f560bc56a59ee63ca4c6a8bfa46ae4ad651af316d4e81817bb9fd88"},
 
1250
  test = ["jaraco.test (>=5.4)", "pytest (>=6,!=8.1.*)", "zipp (>=3.17)"]
1251
  type = ["pytest-mypy"]
1252
 
1253
+ [[package]]
1254
+ name = "iniconfig"
1255
+ version = "2.1.0"
1256
+ description = "brain-dead simple config-ini parsing"
1257
+ optional = false
1258
+ python-versions = ">=3.8"
1259
+ groups = ["dev"]
1260
+ files = [
1261
+ {file = "iniconfig-2.1.0-py3-none-any.whl", hash = "sha256:9deba5723312380e77435581c6bf4935c94cbfab9b1ed33ef8d238ea168eb760"},
1262
+ {file = "iniconfig-2.1.0.tar.gz", hash = "sha256:3abbd2e30b36733fee78f9c7f7308f2d0050e88f0087fd25c2645f63c773e1c7"},
1263
+ ]
1264
+
1265
  [[package]]
1266
  name = "isort"
1267
  version = "6.0.1"
 
1637
  gmpy = ["gmpy2 (>=2.1.0a4) ; platform_python_implementation != \"PyPy\""]
1638
  tests = ["pytest (>=4.6)"]
1639
 
1640
+ [[package]]
1641
+ name = "mypy"
1642
+ version = "1.16.0"
1643
+ description = "Optional static typing for Python"
1644
+ optional = false
1645
+ python-versions = ">=3.9"
1646
+ groups = ["dev"]
1647
+ files = [
1648
+ {file = "mypy-1.16.0-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:7909541fef256527e5ee9c0a7e2aeed78b6cda72ba44298d1334fe7881b05c5c"},
1649
+ {file = "mypy-1.16.0-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:e71d6f0090c2256c713ed3d52711d01859c82608b5d68d4fa01a3fe30df95571"},
1650
+ {file = "mypy-1.16.0-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:936ccfdd749af4766be824268bfe22d1db9eb2f34a3ea1d00ffbe5b5265f5491"},
1651
+ {file = "mypy-1.16.0-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:4086883a73166631307fdd330c4a9080ce24913d4f4c5ec596c601b3a4bdd777"},
1652
+ {file = "mypy-1.16.0-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:feec38097f71797da0231997e0de3a58108c51845399669ebc532c815f93866b"},
1653
+ {file = "mypy-1.16.0-cp310-cp310-win_amd64.whl", hash = "sha256:09a8da6a0ee9a9770b8ff61b39c0bb07971cda90e7297f4213741b48a0cc8d93"},
1654
+ {file = "mypy-1.16.0-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:9f826aaa7ff8443bac6a494cf743f591488ea940dd360e7dd330e30dd772a5ab"},
1655
+ {file = "mypy-1.16.0-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:82d056e6faa508501af333a6af192c700b33e15865bda49611e3d7d8358ebea2"},
1656
+ {file = "mypy-1.16.0-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:089bedc02307c2548eb51f426e085546db1fa7dd87fbb7c9fa561575cf6eb1ff"},
1657
+ {file = "mypy-1.16.0-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6a2322896003ba66bbd1318c10d3afdfe24e78ef12ea10e2acd985e9d684a666"},
1658
+ {file = "mypy-1.16.0-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:021a68568082c5b36e977d54e8f1de978baf401a33884ffcea09bd8e88a98f4c"},
1659
+ {file = "mypy-1.16.0-cp311-cp311-win_amd64.whl", hash = "sha256:54066fed302d83bf5128632d05b4ec68412e1f03ef2c300434057d66866cea4b"},
1660
+ {file = "mypy-1.16.0-cp312-cp312-macosx_10_13_x86_64.whl", hash = "sha256:c5436d11e89a3ad16ce8afe752f0f373ae9620841c50883dc96f8b8805620b13"},
1661
+ {file = "mypy-1.16.0-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:f2622af30bf01d8fc36466231bdd203d120d7a599a6d88fb22bdcb9dbff84090"},
1662
+ {file = "mypy-1.16.0-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:d045d33c284e10a038f5e29faca055b90eee87da3fc63b8889085744ebabb5a1"},
1663
+ {file = "mypy-1.16.0-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b4968f14f44c62e2ec4a038c8797a87315be8df7740dc3ee8d3bfe1c6bf5dba8"},
1664
+ {file = "mypy-1.16.0-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:eb14a4a871bb8efb1e4a50360d4e3c8d6c601e7a31028a2c79f9bb659b63d730"},
1665
+ {file = "mypy-1.16.0-cp312-cp312-win_amd64.whl", hash = "sha256:bd4e1ebe126152a7bbaa4daedd781c90c8f9643c79b9748caa270ad542f12bec"},
1666
+ {file = "mypy-1.16.0-cp313-cp313-macosx_10_13_x86_64.whl", hash = "sha256:a9e056237c89f1587a3be1a3a70a06a698d25e2479b9a2f57325ddaaffc3567b"},
1667
+ {file = "mypy-1.16.0-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:0b07e107affb9ee6ce1f342c07f51552d126c32cd62955f59a7db94a51ad12c0"},
1668
+ {file = "mypy-1.16.0-cp313-cp313-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:c6fb60cbd85dc65d4d63d37cb5c86f4e3a301ec605f606ae3a9173e5cf34997b"},
1669
+ {file = "mypy-1.16.0-cp313-cp313-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a7e32297a437cc915599e0578fa6bc68ae6a8dc059c9e009c628e1c47f91495d"},
1670
+ {file = "mypy-1.16.0-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:afe420c9380ccec31e744e8baff0d406c846683681025db3531b32db56962d52"},
1671
+ {file = "mypy-1.16.0-cp313-cp313-win_amd64.whl", hash = "sha256:55f9076c6ce55dd3f8cd0c6fff26a008ca8e5131b89d5ba6d86bd3f47e736eeb"},
1672
+ {file = "mypy-1.16.0-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:f56236114c425620875c7cf71700e3d60004858da856c6fc78998ffe767b73d3"},
1673
+ {file = "mypy-1.16.0-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:15486beea80be24ff067d7d0ede673b001d0d684d0095803b3e6e17a886a2a92"},
1674
+ {file = "mypy-1.16.0-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.manylinux_2_28_aarch64.whl", hash = "sha256:f2ed0e0847a80655afa2c121835b848ed101cc7b8d8d6ecc5205aedc732b1436"},
1675
+ {file = "mypy-1.16.0-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:eb5fbc8063cb4fde7787e4c0406aa63094a34a2daf4673f359a1fb64050e9cb2"},
1676
+ {file = "mypy-1.16.0-cp39-cp39-musllinux_1_2_x86_64.whl", hash = "sha256:a5fcfdb7318c6a8dd127b14b1052743b83e97a970f0edb6c913211507a255e20"},
1677
+ {file = "mypy-1.16.0-cp39-cp39-win_amd64.whl", hash = "sha256:2e7e0ad35275e02797323a5aa1be0b14a4d03ffdb2e5f2b0489fa07b89c67b21"},
1678
+ {file = "mypy-1.16.0-py3-none-any.whl", hash = "sha256:29e1499864a3888bca5c1542f2d7232c6e586295183320caa95758fc84034031"},
1679
+ {file = "mypy-1.16.0.tar.gz", hash = "sha256:84b94283f817e2aa6350a14b4a8fb2a35a53c286f97c9d30f53b63620e7af8ab"},
1680
+ ]
1681
+
1682
+ [package.dependencies]
1683
+ mypy_extensions = ">=1.0.0"
1684
+ pathspec = ">=0.9.0"
1685
+ tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""}
1686
+ typing_extensions = ">=4.6.0"
1687
+
1688
+ [package.extras]
1689
+ dmypy = ["psutil (>=4.0)"]
1690
+ faster-cache = ["orjson"]
1691
+ install-types = ["pip"]
1692
+ mypyc = ["setuptools (>=50)"]
1693
+ reports = ["lxml"]
1694
+
1695
+ [[package]]
1696
+ name = "mypy-extensions"
1697
+ version = "1.1.0"
1698
+ description = "Type system extensions for programs checked with the mypy type checker."
1699
+ optional = false
1700
+ python-versions = ">=3.8"
1701
+ groups = ["dev"]
1702
+ files = [
1703
+ {file = "mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505"},
1704
+ {file = "mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558"},
1705
+ ]
1706
+
1707
  [[package]]
1708
  name = "numpy"
1709
  version = "2.2.5"
 
2092
  description = "Core utilities for Python packages"
2093
  optional = false
2094
  python-versions = ">=3.8"
2095
+ groups = ["main", "dev"]
2096
  files = [
2097
  {file = "packaging-24.2-py3-none-any.whl", hash = "sha256:09abb1bccd265c01f4a3aa3f7a7db064b36514d2cba19a2f694fe6150451a759"},
2098
  {file = "packaging-24.2.tar.gz", hash = "sha256:c228a6dc5e932d346bc5739379109d49e8853dd8223571c7c5b55260edc0b97f"},
 
2181
  test = ["hypothesis (>=6.46.1)", "pytest (>=7.3.2)", "pytest-xdist (>=2.2.0)"]
2182
  xml = ["lxml (>=4.9.2)"]
2183
 
2184
+ [[package]]
2185
+ name = "pathspec"
2186
+ version = "0.12.1"
2187
+ description = "Utility library for gitignore style pattern matching of file paths."
2188
+ optional = false
2189
+ python-versions = ">=3.8"
2190
+ groups = ["dev"]
2191
+ files = [
2192
+ {file = "pathspec-0.12.1-py3-none-any.whl", hash = "sha256:a0d503e138a4c123b27490a4f7beda6a01c6f288df0e4a8b79c7eb0dc7b4cc08"},
2193
+ {file = "pathspec-0.12.1.tar.gz", hash = "sha256:a482d51503a1ab33b1c67a6c3813a26953dbdc71c31dacaef9a838c4e29f5712"},
2194
+ ]
2195
+
2196
  [[package]]
2197
  name = "pillow"
2198
  version = "11.2.1"
 
2310
  test = ["appdirs (==1.4.4)", "covdefaults (>=2.3)", "pytest (>=8.3.4)", "pytest-cov (>=6)", "pytest-mock (>=3.14)"]
2311
  type = ["mypy (>=1.14.1)"]
2312
 
2313
+ [[package]]
2314
+ name = "pluggy"
2315
+ version = "1.6.0"
2316
+ description = "plugin and hook calling mechanisms for python"
2317
+ optional = false
2318
+ python-versions = ">=3.9"
2319
+ groups = ["dev"]
2320
+ files = [
2321
+ {file = "pluggy-1.6.0-py3-none-any.whl", hash = "sha256:e920276dd6813095e9377c0bc5566d94c932c33b27a3e3945d8389c374dd4746"},
2322
+ {file = "pluggy-1.6.0.tar.gz", hash = "sha256:7dcc130b76258d33b90f61b658791dede3486c3e6bfb003ee5c9bfb396dd22f3"},
2323
+ ]
2324
+
2325
+ [package.extras]
2326
+ dev = ["pre-commit", "tox"]
2327
+ testing = ["coverage", "pytest", "pytest-benchmark"]
2328
+
2329
  [[package]]
2330
  name = "posthog"
2331
  version = "4.0.0"
 
2570
  description = "Pygments is a syntax highlighting package written in Python."
2571
  optional = false
2572
  python-versions = ">=3.8"
2573
+ groups = ["main", "dev"]
2574
  files = [
2575
  {file = "pygments-2.19.1-py3-none-any.whl", hash = "sha256:9ea1544ad55cecf4b8242fab6dd35a93bbce657034b0611ee383099054ab6d8c"},
2576
  {file = "pygments-2.19.1.tar.gz", hash = "sha256:61c16d2a8576dc0649d9f39e089b5f02bcd27fba10d8fb4dcc28173f7a45151f"},
 
2677
  [package.extras]
2678
  dev = ["build", "flake8", "mypy", "pytest", "twine"]
2679
 
2680
+ [[package]]
2681
+ name = "pytest"
2682
+ version = "8.4.0"
2683
+ description = "pytest: simple powerful testing with Python"
2684
+ optional = false
2685
+ python-versions = ">=3.9"
2686
+ groups = ["dev"]
2687
+ files = [
2688
+ {file = "pytest-8.4.0-py3-none-any.whl", hash = "sha256:f40f825768ad76c0977cbacdf1fd37c6f7a468e460ea6a0636078f8972d4517e"},
2689
+ {file = "pytest-8.4.0.tar.gz", hash = "sha256:14d920b48472ea0dbf68e45b96cd1ffda4705f33307dcc86c676c1b5104838a6"},
2690
+ ]
2691
+
2692
+ [package.dependencies]
2693
+ colorama = {version = ">=0.4", markers = "sys_platform == \"win32\""}
2694
+ exceptiongroup = {version = ">=1", markers = "python_version < \"3.11\""}
2695
+ iniconfig = ">=1"
2696
+ packaging = ">=20"
2697
+ pluggy = ">=1.5,<2"
2698
+ pygments = ">=2.7.2"
2699
+ tomli = {version = ">=1", markers = "python_version < \"3.11\""}
2700
+
2701
+ [package.extras]
2702
+ dev = ["argcomplete", "attrs (>=19.2)", "hypothesis (>=3.56)", "mock", "requests", "setuptools", "xmlschema"]
2703
+
2704
  [[package]]
2705
  name = "python-dateutil"
2706
  version = "2.9.0.post0"
 
3785
  [metadata]
3786
  lock-version = "2.1"
3787
  python-versions = ">=3.10,<3.11"
3788
+ content-hash = "5875bda554fa1ca646ca95034228f8405def0517d9b0597042a45c8af59f67c6"
pylint-output.txt ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+
2
+ ------------------------------------
3
+ Your code has been rated at 10.00/10
4
+
pyproject.toml CHANGED
@@ -29,4 +29,7 @@ build-backend = "poetry.core.masonry.api"
29
 
30
  [tool.poetry.group.dev.dependencies]
31
  pylint = "^3.3.7"
 
 
 
32
 
 
29
 
30
  [tool.poetry.group.dev.dependencies]
31
  pylint = "^3.3.7"
32
+ black = "^25.1.0"
33
+ pytest = "^8.4.0"
34
+ mypy = "^1.16.0"
35
 
ragntex.py CHANGED
@@ -4,7 +4,7 @@ import os
4
  from src import demo, init_telemetry
5
 
6
  # Setup OpenTelemetry
7
- init_telemetry()
8
  # Run Gradio
9
  if os.getenv("IN_DOCKER") == "true":
10
  demo.launch(server_name="0.0.0.0", server_port=7860)
 
4
  from src import demo, init_telemetry
5
 
6
  # Setup OpenTelemetry
7
+ _ = init_telemetry()
8
  # Run Gradio
9
  if os.getenv("IN_DOCKER") == "true":
10
  demo.launch(server_name="0.0.0.0", server_port=7860)
src/compilation/latex_compilation.py CHANGED
@@ -25,7 +25,7 @@ def compile_presentation(latex_code, work_dir) -> None:
25
 
26
  # Save LaTeX code to file
27
  tex_file = os.path.join(work_dir, "presentation.tex")
28
- with open(tex_file, "w") as f:
29
  f.write(latex_code)
30
 
31
  LOGGER.info("📄 Files in the directory: %s", work_dir)
 
25
 
26
  # Save LaTeX code to file
27
  tex_file = os.path.join(work_dir, "presentation.tex")
28
+ with open(tex_file, "w", encoding="utf-8") as f:
29
  f.write(latex_code)
30
 
31
  LOGGER.info("📄 Files in the directory: %s", work_dir)
src/database/__init__.py CHANGED
@@ -1,7 +1,6 @@
1
  """This module initializes the database package."""
2
 
3
  from .database import db, embed_fn
4
- from .ingest import ingest_files_to_db
5
- from .retrieve import retrive_files_from_db
6
 
7
  __all__ = ["db", "embed_fn", "ingest_files_to_db", "retrive_files_from_db"]
 
1
  """This module initializes the database package."""
2
 
3
  from .database import db, embed_fn
4
+ from .db_manipulation import ingest_files_to_db, retrive_files_from_db
 
5
 
6
  __all__ = ["db", "embed_fn", "ingest_files_to_db", "retrive_files_from_db"]
src/database/database.py CHANGED
@@ -19,7 +19,7 @@ class GeminiEmbeddingFunction(EmbeddingFunction):
19
  self.document_mode = True
20
 
21
  @retry.Retry(predicate=is_retriable)
22
- def __call__(self, input: Documents) -> Embeddings:
23
  if self.document_mode:
24
  embedding_task = "retrieval_document"
25
  else:
@@ -27,7 +27,7 @@ class GeminiEmbeddingFunction(EmbeddingFunction):
27
 
28
  response = client.models.embed_content(
29
  model="models/text-embedding-004",
30
- contents=input,
31
  config=types.EmbedContentConfig(
32
  task_type=embedding_task,
33
  ),
 
19
  self.document_mode = True
20
 
21
  @retry.Retry(predicate=is_retriable)
22
+ def __call__(self, inputs: Documents) -> Embeddings:
23
  if self.document_mode:
24
  embedding_task = "retrieval_document"
25
  else:
 
27
 
28
  response = client.models.embed_content(
29
  model="models/text-embedding-004",
30
+ contents=inputs,
31
  config=types.EmbedContentConfig(
32
  task_type=embedding_task,
33
  ),
src/database/{ingest.py → db_manipulation.py} RENAMED
@@ -1,9 +1,9 @@
1
- """Ingest module for adding new PDF files to the database."""
2
 
3
- from pathlib import Path
4
- from langfuse.decorators import observe
5
 
6
- from .database import db
7
  from ..telemetry import Logger
8
  from ..processing import process_documents
9
 
@@ -17,10 +17,14 @@ def ingest_files_to_db(pdf_files) -> None:
17
  pdf_files (list): List of PDF files to be ingested.
18
  """
19
  # Get all the existing entries and extract the known filenames
20
- all_entries = db.get(include=["metadatas"])
 
 
 
 
21
  existing_pdfs = set(
22
  meta.get("pdf_path")
23
- for meta in all_entries["metadatas"]
24
  if meta.get("pdf_path")
25
  )
26
 
@@ -42,3 +46,37 @@ def ingest_files_to_db(pdf_files) -> None:
42
  metadatas=metadatas,
43
  )
44
  LOGGER.info("✅ Documents ingested successfully.")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Module for adding and getting PDF files to/from the database."""
2
 
3
+ from typing import Mapping, Union, List
4
+ from langfuse.decorators import langfuse_context, observe
5
 
6
+ from .database import db, embed_fn
7
  from ..telemetry import Logger
8
  from ..processing import process_documents
9
 
 
17
  pdf_files (list): List of PDF files to be ingested.
18
  """
19
  # Get all the existing entries and extract the known filenames
20
+ all_entries = db.get(include=["metadatas"]) or []
21
+
22
+ if not all_entries:
23
+ LOGGER.info("📂 No existing entries in the database. Ingesting all PDFs.")
24
+
25
  existing_pdfs = set(
26
  meta.get("pdf_path")
27
+ for meta in all_entries["metadatas"] # type: ignore[union-attr]
28
  if meta.get("pdf_path")
29
  )
30
 
 
46
  metadatas=metadatas,
47
  )
48
  LOGGER.info("✅ Documents ingested successfully.")
49
+
50
+
51
+ Metadata = Mapping[str, Union[str, int, float, bool]]
52
+ DocumentsBatch = List[List[str]]
53
+ MetadataBatch = List[List[Metadata]]
54
+
55
+
56
+ @observe(name="🔍 retrieve_files_from_db")
57
+ def retrive_files_from_db(topic: str) -> tuple[DocumentsBatch, MetadataBatch]:
58
+ """Retrieve relevant documents from the database based on the provided topic.
59
+ Args:
60
+ topic (str): The topic for which to retrieve documents.
61
+ Returns:
62
+ tuple: A 2-element tuple:
63
+ - list[str]: List of retrieved documents.
64
+ - list[dict]: List of metadata associated with the documents.
65
+ """
66
+ LOGGER.info("🔍 Retrieving relevant documents...")
67
+ embed_fn.document_mode = False
68
+ query_oneline = topic.replace("\n", " ")
69
+
70
+ n_yelded_docs = 2
71
+ result = db.query(query_texts=[query_oneline], n_results=n_yelded_docs)
72
+ langfuse_context.update_current_observation(
73
+ output={
74
+ "input.query_oneline": query_oneline,
75
+ "output.n_results": n_yelded_docs,
76
+ "output.metadatas": result["metadatas"],
77
+ }
78
+ )
79
+ [documents] = result.get("documents") or [[]]
80
+ [metadatas] = result.get("metadatas") or [[]]
81
+
82
+ return [documents], [metadatas]
src/database/retrieve.py DELETED
@@ -1,36 +0,0 @@
1
- import json
2
- from langfuse.decorators import langfuse_context, observe
3
-
4
- from .database import db, embed_fn
5
- from ..telemetry import Logger
6
-
7
- LOGGER = Logger.get_logger()
8
-
9
-
10
- @observe(name="🔍 retrieve_files_from_db")
11
- def retrive_files_from_db(topic: str) -> tuple[list[str], list[dict]]:
12
- """Retrieve relevant documents from the database based on the provided topic.
13
- Args:
14
- topic (str): The topic for which to retrieve documents.
15
- Returns:
16
- tuple: A 2-element tuple:
17
- - list[str]: List of retrieved documents.
18
- - list[dict]: List of metadata associated with the documents.
19
- """
20
- LOGGER.info("🔍 Retrieving relevant documents...")
21
- embed_fn.document_mode = False
22
- query_oneline = topic.replace("\n", " ")
23
-
24
- n_yelded_docs = 2
25
- result = db.query(query_texts=[query_oneline], n_results=n_yelded_docs)
26
- langfuse_context.update_current_observation(
27
- output={
28
- "input.query_oneline": query_oneline,
29
- "output.n_results": n_yelded_docs,
30
- "output.metadatas": result["metadatas"],
31
- }
32
- )
33
- [documents] = result["documents"]
34
- [metadatas] = result["metadatas"]
35
-
36
- return [documents], [metadatas]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
src/generator.py CHANGED
@@ -1,6 +1,5 @@
1
  """Module to put it all together and manage the generation of a presentation."""
2
 
3
- from pathlib import Path
4
  from langfuse.decorators import langfuse_context, observe
5
 
6
  # from datetime import datetime
@@ -9,7 +8,7 @@ from src.telemetry import Logger
9
  from src.processing import get_prompt, create_output_folder
10
  from src.services import client
11
  from src.compilation import compile_presentation
12
- from src.processing import delete_uploaded_files, find_used_gfx
13
 
14
 
15
  LOGGER = Logger.get_logger()
 
1
  """Module to put it all together and manage the generation of a presentation."""
2
 
 
3
  from langfuse.decorators import langfuse_context, observe
4
 
5
  # from datetime import datetime
 
8
  from src.processing import get_prompt, create_output_folder
9
  from src.services import client
10
  from src.compilation import compile_presentation
11
+ from src.processing import find_used_gfx
12
 
13
 
14
  LOGGER = Logger.get_logger()
src/interface/download_files.py CHANGED
@@ -1,3 +1,5 @@
 
 
1
  import zipfile
2
  from pathlib import Path
3
  from ..telemetry.logging_utils import Logger
@@ -10,12 +12,12 @@ def download_files(folder_path) -> str:
10
 
11
  if not folder_path:
12
  return "No folder path provided."
13
-
14
  folder = Path(folder_path)
15
  zip_path = Path.cwd() / "presentation.zip"
16
 
17
- with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
18
- for file in folder.rglob('*'):
19
  if file.is_file() and file != zip_path:
20
  arcname = Path("presentation") / file.relative_to(folder)
21
  zipf.write(file, arcname=arcname)
 
1
+ """Helper module to download files as a zip archive via UI."""
2
+
3
  import zipfile
4
  from pathlib import Path
5
  from ..telemetry.logging_utils import Logger
 
12
 
13
  if not folder_path:
14
  return "No folder path provided."
15
+
16
  folder = Path(folder_path)
17
  zip_path = Path.cwd() / "presentation.zip"
18
 
19
+ with zipfile.ZipFile(zip_path, "w", zipfile.ZIP_DEFLATED) as zipf:
20
+ for file in folder.rglob("*"):
21
  if file.is_file() and file != zip_path:
22
  arcname = Path("presentation") / file.relative_to(folder)
23
  zipf.write(file, arcname=arcname)
src/interface/gradio_interface.py CHANGED
@@ -1,11 +1,12 @@
1
- # interface/gradio_interface.py
 
2
 
 
3
  import gradio as gr
4
  from .upload_files import upload_files
5
  from .download_files import download_files
6
  from ..generator import generate_presentation
7
  from ..telemetry import submit_feedback
8
- import base64
9
 
10
 
11
  def upload_and_update_list(files: list, uploaded_list) -> tuple[str, list[str]]:
@@ -22,20 +23,24 @@ def upload_and_update_list(files: list, uploaded_list) -> tuple[str, list[str]]:
22
  return status, updated_list
23
 
24
 
25
- def generate_iframe(folder_path):
 
 
 
 
 
 
26
  file_path = f"{folder_path}/presentation.pdf"
27
  if not file_path:
28
  return ""
29
- else:
30
- with open(file_path, "rb") as f:
31
- base64_pdf = base64.b64encode(f.read()).decode("utf-8")
32
- pdf_display = f"""
33
- <div style="position:relative; width:100%; padding-top:76.5%;">
34
- <iframe src="data:application/pdf;base64,{base64_pdf}#view=FitH"
35
- style="position:absolute; top:0; left:0; width:100%; height:100%; border:none;">
36
- </iframe></div>
37
- """
38
- # pdf_display = f'<iframe width="100%" height="600" src="data:application/pdf;base64,{base64_pdf}"></iframe>'
39
  return pdf_display
40
 
41
 
@@ -55,7 +60,7 @@ theme = gr.themes.Monochrome(
55
  ),
56
  ).set(body_background_fill="*neutral_50", body_text_color="*neutral_950")
57
 
58
- js_func = """
59
  function refresh() {
60
  const url = new URL(window.location);
61
 
@@ -67,17 +72,23 @@ function refresh() {
67
  """
68
 
69
 
70
- def encode_image(image_path):
 
 
 
 
 
 
71
  with open(image_path, "rb") as f:
72
  data = f.read()
73
  return f"data:image/png;base64,{base64.b64encode(data).decode()}"
74
 
75
 
76
- image_base64 = encode_image("gfx/long_logo.png")
77
- github_base64 = encode_image("gfx/github-mark-white.png")
78
 
79
 
80
- with gr.Blocks(theme=theme, js=js_func) as demo:
81
  uploaded_files_state = gr.State([])
82
  presentation_folder_state = gr.State("")
83
 
@@ -102,7 +113,7 @@ with gr.Blocks(theme=theme, js=js_func) as demo:
102
  gr.HTML(
103
  f"""
104
  <div style="text-align:center;">
105
- <img src="{image_base64}" style="max-width: 100%; height: auto;" />
106
  </div>
107
  """
108
  )
@@ -291,7 +302,7 @@ with gr.Blocks(theme=theme, js=js_func) as demo:
291
  onmouseover="this.style.backgroundColor='#6d28d9';"
292
  onmouseout="this.style.backgroundColor='#4c1d95';"
293
  >
294
- <img src="{github_base64}" alt="GitHub" style="height: 20px; margin: 0;">
295
  RAG'n'TeX
296
  </a>
297
  </div>
 
1
+ # pylint: disable=no-member, line-too-long
2
+ """Gradio UI for the RAG'n'TeX LaTeX Presentation Generator."""
3
 
4
+ import base64
5
  import gradio as gr
6
  from .upload_files import upload_files
7
  from .download_files import download_files
8
  from ..generator import generate_presentation
9
  from ..telemetry import submit_feedback
 
10
 
11
 
12
  def upload_and_update_list(files: list, uploaded_list) -> tuple[str, list[str]]:
 
23
  return status, updated_list
24
 
25
 
26
+ def generate_iframe(folder_path) -> str:
27
+ """Generate an HTML iframe to display the PDF presentation.
28
+ Args:
29
+ folder_path (str): Path to the folder containing the generated PDF presentation.
30
+ Returns:
31
+ str: HTML string containing the iframe to display the PDF.
32
+ """
33
  file_path = f"{folder_path}/presentation.pdf"
34
  if not file_path:
35
  return ""
36
+ with open(file_path, "rb") as f:
37
+ base64_pdf = base64.b64encode(f.read()).decode("utf-8")
38
+ pdf_display = f"""
39
+ <div style="position:relative; width:100%; padding-top:76.5%;">
40
+ <iframe src="data:application/pdf;base64,{base64_pdf}#view=FitH"
41
+ style="position:absolute; top:0; left:0; width:100%; height:100%; border:none;">
42
+ </iframe></div>
43
+ """
 
 
44
  return pdf_display
45
 
46
 
 
60
  ),
61
  ).set(body_background_fill="*neutral_50", body_text_color="*neutral_950")
62
 
63
+ JS_FUNC = """
64
  function refresh() {
65
  const url = new URL(window.location);
66
 
 
72
  """
73
 
74
 
75
+ def encode_image(image_path) -> str:
76
+ """Encode an image file to a base64 string for embedding in HTML.
77
+ Args:
78
+ image_path (str): Path to the image file.
79
+ Returns:
80
+ str: Base64 encoded string of the image, prefixed with the appropriate data URI scheme.
81
+ """
82
  with open(image_path, "rb") as f:
83
  data = f.read()
84
  return f"data:image/png;base64,{base64.b64encode(data).decode()}"
85
 
86
 
87
+ IMAGE_BASE64 = encode_image("gfx/long_logo.png")
88
+ GITHUB_BASE64 = encode_image("gfx/github-mark-white.png")
89
 
90
 
91
+ with gr.Blocks(theme=theme, js=JS_FUNC) as demo:
92
  uploaded_files_state = gr.State([])
93
  presentation_folder_state = gr.State("")
94
 
 
113
  gr.HTML(
114
  f"""
115
  <div style="text-align:center;">
116
+ <img src="{IMAGE_BASE64}" style="max-width: 100%; height: auto;" />
117
  </div>
118
  """
119
  )
 
302
  onmouseover="this.style.backgroundColor='#6d28d9';"
303
  onmouseout="this.style.backgroundColor='#4c1d95';"
304
  >
305
+ <img src="{GITHUB_BASE64}" alt="GitHub" style="height: 20px; margin: 0;">
306
  RAG'n'TeX
307
  </a>
308
  </div>
src/interface/upload_files.py CHANGED
@@ -21,8 +21,8 @@ def upload_files(files: list) -> tuple[str, list[str]]:
21
 
22
  current_file = Path(__file__).resolve()
23
  project_root = current_file.parents[2] # utils → src → PROJECT ROOT
24
- UPLOAD_DIR = project_root / "uploaded_docs"
25
- UPLOAD_DIR.mkdir(parents=True, exist_ok=True)
26
 
27
  messages = []
28
  saved_paths = []
@@ -31,7 +31,7 @@ def upload_files(files: list) -> tuple[str, list[str]]:
31
  try:
32
  temp_path = Path(file.name)
33
  file_name = temp_path.name.replace(" ", "_")
34
- target_path = UPLOAD_DIR / file_name
35
 
36
  if target_path.exists():
37
  messages.append(f"⚠️ File already exists: {file_name}")
@@ -40,14 +40,14 @@ def upload_files(files: list) -> tuple[str, list[str]]:
40
  if not temp_path.exists():
41
  messages.append(f"❌ File not found: {file_name}")
42
  continue
43
- else:
44
- shutil.move(str(temp_path), str(target_path))
45
- messages.append(f"✅ Uploaded new file: {file_name}")
46
- LOGGER.info("📤 Uploaded file %s to %s", file_name, UPLOAD_DIR)
47
 
48
  saved_paths.append(str(target_path))
49
 
50
- except Exception as e:
51
  LOGGER.error("❌ Error uploading %s", file_name, exc_info=e)
52
  messages.append(f"❌ Error uploading {file_name}: {e}")
53
 
 
21
 
22
  current_file = Path(__file__).resolve()
23
  project_root = current_file.parents[2] # utils → src → PROJECT ROOT
24
+ upload_dir = project_root / "uploaded_docs"
25
+ upload_dir.mkdir(parents=True, exist_ok=True)
26
 
27
  messages = []
28
  saved_paths = []
 
31
  try:
32
  temp_path = Path(file.name)
33
  file_name = temp_path.name.replace(" ", "_")
34
+ target_path = upload_dir / file_name
35
 
36
  if target_path.exists():
37
  messages.append(f"⚠️ File already exists: {file_name}")
 
40
  if not temp_path.exists():
41
  messages.append(f"❌ File not found: {file_name}")
42
  continue
43
+
44
+ shutil.move(str(temp_path), str(target_path))
45
+ messages.append(f"✅ Uploaded new file: {file_name}")
46
+ LOGGER.info("📤 Uploaded file %s to %s", file_name, upload_dir)
47
 
48
  saved_paths.append(str(target_path))
49
 
50
+ except (FileNotFoundError, PermissionError, shutil.Error, OSError) as e:
51
  LOGGER.error("❌ Error uploading %s", file_name, exc_info=e)
52
  messages.append(f"❌ Error uploading {file_name}: {e}")
53
 
src/processing/document_processing.py CHANGED
@@ -2,7 +2,6 @@
2
 
3
  import re
4
  import os
5
- import json
6
  from pathlib import Path
7
  import fitz
8
  from langfuse.decorators import langfuse_context, observe
@@ -14,7 +13,7 @@ LOGGER = Logger.get_logger()
14
 
15
 
16
  @observe(name="⚙️ extract_pdf_content")
17
- def extract_pdf_content(pdf_path: str):
18
  """Extract text and images from a PDF file.
19
  Args:
20
  pdf_path (str): Path to the PDF file.
@@ -37,7 +36,7 @@ def extract_pdf_content(pdf_path: str):
37
  figs += extract_images(pdf, doc, page, page_num)
38
 
39
  # Extract vector graphics
40
- figs += extract_vector(pdf, doc, page, page_num)
41
 
42
  # Format the metadata
43
  metas = {"num_images": len(figs), "pdf_path": pdf_path}
@@ -47,7 +46,15 @@ def extract_pdf_content(pdf_path: str):
47
 
48
 
49
  @observe(name="📊 process_documents")
50
- def process_documents(pdf_files):
 
 
 
 
 
 
 
 
51
  documents = []
52
  metadatas = []
53
 
@@ -58,12 +65,10 @@ def process_documents(pdf_files):
58
 
59
  # Format images
60
  images_info = []
61
- for i, img in enumerate(imgs, start=1):
62
  caption = img.get("caption")
63
  caption_str = str(caption) if caption is not None else ""
64
- img_name = img["name"]
65
- img_ratio = img["ratio"]
66
- full_path = f"gfx/{img_name}"
67
 
68
  cleaned_caption = re.sub(
69
  r"^(fig(?:ure)?\.?\s*\d+\.\s*)",
@@ -74,7 +79,11 @@ def process_documents(pdf_files):
74
  caption = cleaned_caption if cleaned_caption else "None"
75
 
76
  images_info.append(
77
- f'{{"path": "{full_path}", "caption": "{caption}", "orientation": "{img_ratio}"}}'
 
 
 
 
78
  )
79
 
80
  images_passage = "\n".join(images_info)
@@ -99,8 +108,12 @@ def process_documents(pdf_files):
99
  return documents, metadatas
100
 
101
 
102
- def delete_uploaded_files(uploaded_files):
103
- """Delete uploaded files after processing."""
 
 
 
 
104
  for file in uploaded_files:
105
  try:
106
  path = Path(file)
@@ -110,5 +123,5 @@ def delete_uploaded_files(uploaded_files):
110
  else:
111
  LOGGER.warning(f"File not found for deletion: {file}")
112
  LOGGER.info("🧹 Cleaned up uploaded files.")
113
- except Exception as e:
114
  LOGGER.warning(f"Failed to delete {file}", exc_info=e)
 
2
 
3
  import re
4
  import os
 
5
  from pathlib import Path
6
  import fitz
7
  from langfuse.decorators import langfuse_context, observe
 
13
 
14
 
15
  @observe(name="⚙️ extract_pdf_content")
16
+ def extract_pdf_content(pdf_path: str) -> tuple[str, list[dict], dict]:
17
  """Extract text and images from a PDF file.
18
  Args:
19
  pdf_path (str): Path to the PDF file.
 
36
  figs += extract_images(pdf, doc, page, page_num)
37
 
38
  # Extract vector graphics
39
+ figs += extract_vector(pdf, page, page_num)
40
 
41
  # Format the metadata
42
  metas = {"num_images": len(figs), "pdf_path": pdf_path}
 
46
 
47
 
48
  @observe(name="📊 process_documents")
49
+ def process_documents(pdf_files) -> tuple[list[str], list[dict]]:
50
+ """Process a list of PDF files to extract text and images metadata.
51
+ Args:
52
+ pdf_files (list): List of paths to PDF files.
53
+ Returns:
54
+ tuple: A 2-element tuple:
55
+ - list[str]: List of extracted text from each PDF.
56
+ - list[dict]: List of metadata dictionaries for each PDF.
57
+ """
58
  documents = []
59
  metadatas = []
60
 
 
65
 
66
  # Format images
67
  images_info = []
68
+ for _, img in enumerate(imgs, start=1):
69
  caption = img.get("caption")
70
  caption_str = str(caption) if caption is not None else ""
71
+ full_path = f"gfx/{img['name']}"
 
 
72
 
73
  cleaned_caption = re.sub(
74
  r"^(fig(?:ure)?\.?\s*\d+\.\s*)",
 
79
  caption = cleaned_caption if cleaned_caption else "None"
80
 
81
  images_info.append(
82
+ (
83
+ f'{{"path": "{full_path}", '
84
+ f'"caption": "{caption}", '
85
+ f'"orientation": "{img["ratio"]}"}}'
86
+ )
87
  )
88
 
89
  images_passage = "\n".join(images_info)
 
108
  return documents, metadatas
109
 
110
 
111
+ @observe(name="🗑️ delete_uploaded_files")
112
+ def delete_uploaded_files(uploaded_files) -> None:
113
+ """Delete uploaded files after processing.
114
+ Args:
115
+ uploaded_files (list): List of file paths to be deleted.
116
+ """
117
  for file in uploaded_files:
118
  try:
119
  path = Path(file)
 
123
  else:
124
  LOGGER.warning(f"File not found for deletion: {file}")
125
  LOGGER.info("🧹 Cleaned up uploaded files.")
126
+ except (OSError, PermissionError) as e:
127
  LOGGER.warning(f"Failed to delete {file}", exc_info=e)
src/processing/images_processing.py CHANGED
@@ -4,6 +4,7 @@ import re
4
  import os
5
  import hashlib
6
  import json
 
7
  from collections import defaultdict
8
  import fitz
9
  from rtree import index
@@ -14,8 +15,16 @@ from ..telemetry import Logger
14
  LOGGER = Logger.get_logger()
15
 
16
 
17
- def find_image_caption(page, image_bbox, max_distance=100):
18
- """Method to find and extract image caption based on the image bounding box."""
 
 
 
 
 
 
 
 
19
  # Get all text blocks on the page
20
  blocks = page.get_text("dict")["blocks"]
21
  image_bottom = image_bbox.y1
@@ -30,7 +39,7 @@ def find_image_caption(page, image_bbox, max_distance=100):
30
  continue
31
 
32
  block_bbox = block["bbox"]
33
- x0, y0, x1, y1 = block_bbox
34
  vertical_distance = y0 - image_bottom
35
 
36
  # Merge all spans' text into one string
@@ -51,20 +60,30 @@ def find_image_caption(page, image_bbox, max_distance=100):
51
  if re.match(r"^(Fig(ure)?\.?\s*\d+[:\-])", block_text, re.IGNORECASE):
52
  best_match_caption = block_text
53
  break
54
- else:
55
- fallback_caption = block_text
56
- closest_distance = vertical_distance
57
 
58
  if best_match_caption and len(best_match_caption.strip()) > 10:
59
  return best_match_caption.strip()
60
- elif fallback_caption and len(fallback_caption.strip()) > 10:
61
  return fallback_caption.strip()
62
- else:
63
- return None
64
 
65
 
66
- def extract_images(pdf, doc, page, page_num):
67
- """Extract images from a PDF page and classify them based on their aspect ratio."""
 
 
 
 
 
 
 
 
 
 
 
 
68
  images = page.get_images(full=True)
69
  imgs = []
70
  for img_index, img in enumerate(images):
@@ -86,7 +105,7 @@ def extract_images(pdf, doc, page, page_num):
86
  # Get the image ratio
87
  width = image_bbox.width
88
  height = image_bbox.height
89
- ratio = width / height if height != 0 else None
90
 
91
  # Classify the image based on the ratio
92
  if ratio >= 1.5:
@@ -112,7 +131,15 @@ def extract_images(pdf, doc, page, page_num):
112
  return imgs
113
 
114
 
115
- def are_bounding_boxes_close(bbox1, bbox2, threshold=50):
 
 
 
 
 
 
 
 
116
  # Extracting the four edges of each bounding box
117
  left1, top1, right1, bottom1 = bbox1
118
  left2, top2, right2, bottom2 = bbox2
@@ -126,7 +153,13 @@ def are_bounding_boxes_close(bbox1, bbox2, threshold=50):
126
  )
127
 
128
 
129
- def merge_bounding_boxes(bboxes):
 
 
 
 
 
 
130
  if not bboxes:
131
  return None
132
  # Start with the first bounding box
@@ -136,7 +169,14 @@ def merge_bounding_boxes(bboxes):
136
  return combined_bbox
137
 
138
 
139
- def group_bounding_boxes(bboxes, max_drawings=2000, threshold=50):
 
 
 
 
 
 
 
140
  # R-tree index setup
141
  idx = index.Index()
142
  for i, rect in enumerate(bboxes):
@@ -165,7 +205,7 @@ def group_bounding_boxes(bboxes, max_drawings=2000, threshold=50):
165
  # Find all connected components using DFS
166
  for i in range(len(bboxes)):
167
  if not visited[i]:
168
- component = []
169
  dfs(i, component)
170
  components.append(component)
171
 
@@ -173,7 +213,15 @@ def group_bounding_boxes(bboxes, max_drawings=2000, threshold=50):
173
  return [merge_bounding_boxes(group) for group in components]
174
 
175
 
176
- def process_large_drawing(drawings, max_drawings=1000, threshold=50):
 
 
 
 
 
 
 
 
177
  bboxes = [fitz.Rect(d["rect"]) for d in drawings if d.get("rect")]
178
 
179
  if len(bboxes) < max_drawings:
@@ -192,7 +240,15 @@ def process_large_drawing(drawings, max_drawings=1000, threshold=50):
192
  return group_bounding_boxes(all_results, threshold=threshold)
193
 
194
 
195
- def find_surrounding_text(page, group, threshold=50):
 
 
 
 
 
 
 
 
196
  text_blocks = page.get_text("dict")["blocks"]
197
  expanded = group + (-threshold, -threshold, threshold, threshold)
198
  surrounding = []
@@ -208,12 +264,26 @@ def find_surrounding_text(page, group, threshold=50):
208
  return surrounding
209
 
210
 
211
- def extract_vector(pdf, doc, page, page_num):
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  MAX_DRAWINGS = 1000
213
  MIN_SIZE = 0.05
214
  MAX_SIZE = 0.30
215
  THRESHOLD = 5
216
  ZOOM = 4
 
217
 
218
  page_size = page.rect.width * page.rect.height
219
  min_size = page_size * MIN_SIZE
@@ -236,10 +306,14 @@ def extract_vector(pdf, doc, page, page_num):
236
  figure_bbox = group
237
 
238
  # Filter by minimal plot size
239
- width = figure_bbox[2] - figure_bbox[0]
240
- height = figure_bbox[3] - figure_bbox[1]
 
 
 
 
241
  area = width * height
242
- if area > min_size and area < max_size:
243
  scale_mat = fitz.Matrix(ZOOM, ZOOM)
244
  figure_pix = page.get_pixmap(matrix=scale_mat, clip=figure_bbox)
245
  figure_bytes = figure_pix.tobytes("png")
@@ -249,7 +323,7 @@ def extract_vector(pdf, doc, page, page_num):
249
  )
250
 
251
  # Get the figure ratio
252
- ratio = width / height if height != 0 else None
253
 
254
  # Classify the image based on the ratio
255
  if ratio >= 1.5:
@@ -275,8 +349,15 @@ def extract_vector(pdf, doc, page, page_num):
275
  return figs
276
 
277
 
278
- def save_pdf_images(pdf_path: str, req_imgs: list, images_dir: str):
279
- """Save images used in the presentation to the specified directory."""
 
 
 
 
 
 
 
280
  doc = fitz.open(pdf_path)
281
  pdf = os.path.splitext(os.path.basename(pdf_path))[0]
282
 
@@ -315,7 +396,15 @@ def save_pdf_images(pdf_path: str, req_imgs: list, images_dir: str):
315
  return True
316
 
317
 
318
- def save_pdf_figures(pdf_path: str, req_figs: list, figures_dir: str):
 
 
 
 
 
 
 
 
319
  doc = fitz.open(pdf_path)
320
  pdf = os.path.splitext(os.path.basename(pdf_path))[0]
321
 
@@ -327,11 +416,13 @@ def save_pdf_figures(pdf_path: str, req_figs: list, figures_dir: str):
327
 
328
  for page_num, page in enumerate(doc):
329
  if page_num in pages_to_inspect:
 
330
  MAX_DRAWINGS = 1000
331
  MIN_SIZE = 0.05
332
  MAX_SIZE = 0.30
333
  THRESHOLD = 5
334
  ZOOM = 4
 
335
 
336
  page_size = page.rect.width * page.rect.height
337
  min_size = page_size * MIN_SIZE
@@ -353,10 +444,14 @@ def save_pdf_figures(pdf_path: str, req_figs: list, figures_dir: str):
353
  figure_bbox = group
354
 
355
  # Filter by minimal plot size
356
- width = figure_bbox[2] - figure_bbox[0]
357
- height = figure_bbox[3] - figure_bbox[1]
 
 
 
 
358
  area = width * height
359
- if area > min_size and area < max_size:
360
  scale_mat = fitz.Matrix(ZOOM, ZOOM)
361
  figure_pix = page.get_pixmap(matrix=scale_mat, clip=figure_bbox)
362
  figure_bytes = figure_pix.tobytes("png")
@@ -381,7 +476,7 @@ def save_pdf_figures(pdf_path: str, req_figs: list, figures_dir: str):
381
 
382
 
383
  @observe(name="🔍 find_used_gfx")
384
- def find_used_gfx(answer, work_dir: str, metadatas: list):
385
  """Finds and saves the figures used in the LLM output to the gfx directory
386
  where the presentation will be compiled.
387
  Args:
 
4
  import os
5
  import hashlib
6
  import json
7
+ from typing import Optional
8
  from collections import defaultdict
9
  import fitz
10
  from rtree import index
 
15
  LOGGER = Logger.get_logger()
16
 
17
 
18
+ def find_image_caption(page, image_bbox, max_distance=100) -> Optional[str]:
19
+ """Method to find and extract image caption based on the image bounding box.
20
+ Args:
21
+ page (fitz.Page): The page object from which to extract the caption.
22
+ image_bbox (fitz.Rect): The bounding box of the image.
23
+ max_distance (int): The maximum vertical distance from the image bottom to consider
24
+ a text block as a potential caption.
25
+ Returns:
26
+ str: The extracted caption text if found, otherwise None.
27
+ """
28
  # Get all text blocks on the page
29
  blocks = page.get_text("dict")["blocks"]
30
  image_bottom = image_bbox.y1
 
39
  continue
40
 
41
  block_bbox = block["bbox"]
42
+ x0, y0, x1, _ = block_bbox
43
  vertical_distance = y0 - image_bottom
44
 
45
  # Merge all spans' text into one string
 
60
  if re.match(r"^(Fig(ure)?\.?\s*\d+[:\-])", block_text, re.IGNORECASE):
61
  best_match_caption = block_text
62
  break
63
+ fallback_caption = block_text
64
+ closest_distance = vertical_distance
 
65
 
66
  if best_match_caption and len(best_match_caption.strip()) > 10:
67
  return best_match_caption.strip()
68
+ if fallback_caption and len(fallback_caption.strip()) > 10:
69
  return fallback_caption.strip()
70
+ return None
 
71
 
72
 
73
+ def extract_images(pdf, doc, page, page_num) -> list[dict]:
74
+ """Extract images from a PDF page and classify them based on their aspect ratio.
75
+ Args:
76
+ pdf (str): The PDF filename without extension.
77
+ doc (fitz.Document): The PDF document object.
78
+ page (fitz.Page): The PDF page object.
79
+ page_num (int): The page number in the PDF document.
80
+ Returns:
81
+ list: A list of dictionaries containing image metadata, including:
82
+ - "name": The name of the image file.
83
+ - "caption": The caption of the image, if found.
84
+ - "ratio": The aspect ratio classification of the image ("horizontal", "vertical", or "square").
85
+ - "hash": The MD5 hash of the image content.
86
+ """
87
  images = page.get_images(full=True)
88
  imgs = []
89
  for img_index, img in enumerate(images):
 
105
  # Get the image ratio
106
  width = image_bbox.width
107
  height = image_bbox.height
108
+ ratio = width / height if height != 0 else 2
109
 
110
  # Classify the image based on the ratio
111
  if ratio >= 1.5:
 
131
  return imgs
132
 
133
 
134
+ def are_bounding_boxes_close(bbox1, bbox2, threshold=50) -> bool:
135
+ """Check if two bounding boxes are close to each other based on their edges.
136
+ Args:
137
+ bbox1 (tuple): The first bounding box as a tuple (left, top, right, bottom).
138
+ bbox2 (tuple): The second bounding box as a tuple (left, top, right, bottom).
139
+ threshold (int): The distance threshold to consider two boxes as close.
140
+ Returns:
141
+ bool: True if the bounding boxes are close, False otherwise.
142
+ """
143
  # Extracting the four edges of each bounding box
144
  left1, top1, right1, bottom1 = bbox1
145
  left2, top2, right2, bottom2 = bbox2
 
153
  )
154
 
155
 
156
+ def merge_bounding_boxes(bboxes) -> Optional[fitz.Rect]:
157
+ """Merge a list of bounding boxes into a single bounding box.
158
+ Args:
159
+ bboxes (list): A list of bounding boxes, each represented as a tuple (left, top, right, bottom).
160
+ Returns:
161
+ fitz.Rect: A single bounding box that encompasses all input bounding boxes.
162
+ """
163
  if not bboxes:
164
  return None
165
  # Start with the first bounding box
 
169
  return combined_bbox
170
 
171
 
172
+ def group_bounding_boxes(bboxes, threshold=50) -> list:
173
+ """Group bounding boxes that are close to each other into larger bounding boxes.
174
+ Args:
175
+ bboxes (list): A list of bounding boxes, each represented as a tuple (left, top, right, bottom).
176
+ threshold (int): The distance threshold to consider two boxes as close.
177
+ Returns:
178
+ list: A list of merged bounding boxes, where each box represents a group of close bounding boxes.
179
+ """
180
  # R-tree index setup
181
  idx = index.Index()
182
  for i, rect in enumerate(bboxes):
 
205
  # Find all connected components using DFS
206
  for i in range(len(bboxes)):
207
  if not visited[i]:
208
+ component = [] # type: ignore
209
  dfs(i, component)
210
  components.append(component)
211
 
 
213
  return [merge_bounding_boxes(group) for group in components]
214
 
215
 
216
+ def process_large_drawing(drawings, max_drawings=1000, threshold=50) -> list:
217
+ """Process a large number of drawings by grouping them into bounding boxes.
218
+ Args:
219
+ drawings (list): A list of drawing dictionaries, each containing a "rect" key with bounding box coordinates.
220
+ max_drawings (int): Maximum number of drawings to process at once.
221
+ threshold (int): The distance threshold to consider two boxes as close.
222
+ Returns:
223
+ list: A list of merged bounding boxes, where each box represents a group of close drawings.
224
+ """
225
  bboxes = [fitz.Rect(d["rect"]) for d in drawings if d.get("rect")]
226
 
227
  if len(bboxes) < max_drawings:
 
240
  return group_bounding_boxes(all_results, threshold=threshold)
241
 
242
 
243
+ def find_surrounding_text(page, group, threshold=50) -> list:
244
+ """Find text blocks surrounding a given bounding box on a PDF page.
245
+ Args:
246
+ page (fitz.Page): The PDF page object.
247
+ group (fitz.Rect): The bounding box of the group of drawings.
248
+ threshold (int): The distance threshold to consider a text block as surrounding.
249
+ Returns:
250
+ list: A list of bounding boxes of surrounding text blocks.
251
+ """
252
  text_blocks = page.get_text("dict")["blocks"]
253
  expanded = group + (-threshold, -threshold, threshold, threshold)
254
  surrounding = []
 
264
  return surrounding
265
 
266
 
267
+ def extract_vector(pdf, page, page_num) -> list[dict]:
268
+ """Extract vector graphics from a PDF page and classify them based on their aspect ratio.
269
+ Args:
270
+ pdf (str): The PDF filename without extension.
271
+ page (fitz.Page): The PDF page object.
272
+ page_num (int): The page number in the PDF document.
273
+ Returns:
274
+ list: A list of dictionaries containing figure metadata, including:
275
+ - "name": The name of the figure file.
276
+ - "caption": The caption of the figure, if found.
277
+ - "ratio": The aspect ratio classification of the figure ("horizontal", "vertical", or "square").
278
+ - "hash": The MD5 hash of the figure content.
279
+ """
280
+ # pylint: disable=invalid-name
281
  MAX_DRAWINGS = 1000
282
  MIN_SIZE = 0.05
283
  MAX_SIZE = 0.30
284
  THRESHOLD = 5
285
  ZOOM = 4
286
+ # pylint: enable=invalid-name
287
 
288
  page_size = page.rect.width * page.rect.height
289
  min_size = page_size * MIN_SIZE
 
306
  figure_bbox = group
307
 
308
  # Filter by minimal plot size
309
+ if figure_bbox is not None:
310
+ width = figure_bbox[2] - figure_bbox[0]
311
+ height = figure_bbox[3] - figure_bbox[1]
312
+ else:
313
+ width = height = 0
314
+
315
  area = width * height
316
+ if min_size < area < max_size:
317
  scale_mat = fitz.Matrix(ZOOM, ZOOM)
318
  figure_pix = page.get_pixmap(matrix=scale_mat, clip=figure_bbox)
319
  figure_bytes = figure_pix.tobytes("png")
 
323
  )
324
 
325
  # Get the figure ratio
326
+ ratio = width / height if height != 0 else 2
327
 
328
  # Classify the image based on the ratio
329
  if ratio >= 1.5:
 
349
  return figs
350
 
351
 
352
+ def save_pdf_images(pdf_path: str, req_imgs: list, images_dir: str) -> bool:
353
+ """Save images used in the presentation to the specified directory.
354
+ Args:
355
+ pdf_path (str): Path to the PDF file.
356
+ req_imgs (list): List of dictionaries containing required images metadata.
357
+ images_dir (str): Directory where the images will be saved.
358
+ Returns:
359
+ bool: True if images were saved successfully, False otherwise.
360
+ """
361
  doc = fitz.open(pdf_path)
362
  pdf = os.path.splitext(os.path.basename(pdf_path))[0]
363
 
 
396
  return True
397
 
398
 
399
+ def save_pdf_figures(pdf_path: str, req_figs: list, figures_dir: str) -> bool:
400
+ """Save figures used in the presentation to the specified directory.
401
+ Args:
402
+ pdf_path (str): Path to the PDF file.
403
+ req_figs (list): List of dictionaries containing required figures metadata.
404
+ figures_dir (str): Directory where the figures will be saved.
405
+ Returns:
406
+ bool: True if figures were saved successfully, False otherwise.
407
+ """
408
  doc = fitz.open(pdf_path)
409
  pdf = os.path.splitext(os.path.basename(pdf_path))[0]
410
 
 
416
 
417
  for page_num, page in enumerate(doc):
418
  if page_num in pages_to_inspect:
419
+ # pylint: disable=invalid-name
420
  MAX_DRAWINGS = 1000
421
  MIN_SIZE = 0.05
422
  MAX_SIZE = 0.30
423
  THRESHOLD = 5
424
  ZOOM = 4
425
+ # pylint: enable=invalid-name
426
 
427
  page_size = page.rect.width * page.rect.height
428
  min_size = page_size * MIN_SIZE
 
444
  figure_bbox = group
445
 
446
  # Filter by minimal plot size
447
+ if figure_bbox is not None:
448
+ width = figure_bbox[2] - figure_bbox[0]
449
+ height = figure_bbox[3] - figure_bbox[1]
450
+ else:
451
+ width = height = 0
452
+
453
  area = width * height
454
+ if min_size < area < max_size:
455
  scale_mat = fitz.Matrix(ZOOM, ZOOM)
456
  figure_pix = page.get_pixmap(matrix=scale_mat, clip=figure_bbox)
457
  figure_bytes = figure_pix.tobytes("png")
 
476
 
477
 
478
  @observe(name="🔍 find_used_gfx")
479
+ def find_used_gfx(answer, work_dir: str, metadatas: list) -> None:
480
  """Finds and saves the figures used in the LLM output to the gfx directory
481
  where the presentation will be compiled.
482
  Args:
src/processing/prompt.py CHANGED
@@ -13,9 +13,10 @@ def get_prompt(
13
  str: the prompt with the specified themes and structure for generating a
14
  LaTeX Beamer presentation.
15
  """
16
- prompt = f"""You are a presentation assistant that creates clear, concise, and engaging slide decks from the
17
- reference material provided. You extract the most relevant and important information, organize it logically,
18
- and generate LaTeX code for a presentation using the Beamer class.
 
19
 
20
  Structure your slides as follows:
21
  1. **Introduction**: Present the topic and explain why it's important or interesting.
@@ -100,7 +101,8 @@ def get_prompt(
100
 
101
  \\end{{document}}
102
 
103
- You must use **at least one image** when creating a presentation. In your output, include `\\includegraphics`
 
104
  commands in **at least half of the slides** where appropriate.
105
 
106
  Prioritize the slide structure of **Core Idea 2** (two-column layout) over **Core Idea 3** (single image on top).
@@ -117,6 +119,7 @@ def get_prompt(
117
  command. All image formatting options (height, width, keepaspectratio) must be left untouched.
118
  - Skip any image with caption `"None"`.
119
  - Use **Core Idea 2** layout for **vertical** and **square** images.
120
- - Use **Core Idea 3** layout for **horizontal** images (when a two-column layout is not suitable).\n\n"""
 
121
 
122
  return prompt
 
13
  str: the prompt with the specified themes and structure for generating a
14
  LaTeX Beamer presentation.
15
  """
16
+ prompt = f"""You are a presentation assistant that creates clear, concise, and engaging
17
+ slide decks from the reference material provided. You extract the most relevant and important
18
+ information, organize it logically, and generate LaTeX code for a presentation using
19
+ the Beamer class.
20
 
21
  Structure your slides as follows:
22
  1. **Introduction**: Present the topic and explain why it's important or interesting.
 
101
 
102
  \\end{{document}}
103
 
104
+ You must use **at least one image** when creating a presentation.
105
+ In your output, include `\\includegraphics`
106
  commands in **at least half of the slides** where appropriate.
107
 
108
  Prioritize the slide structure of **Core Idea 2** (two-column layout) over **Core Idea 3** (single image on top).
 
119
  command. All image formatting options (height, width, keepaspectratio) must be left untouched.
120
  - Skip any image with caption `"None"`.
121
  - Use **Core Idea 2** layout for **vertical** and **square** images.
122
+ - Use **Core Idea 3** layout for **horizontal** images
123
+ (when a two-column layout is not suitable).\n\n"""
124
 
125
  return prompt
src/telemetry/logging_utils.py CHANGED
@@ -40,4 +40,5 @@ class Logger:
40
  """
41
  if cls._logger is None:
42
  cls.setup_logging() # Ensure logging is set up before returning the logger
 
43
  return cls._logger
 
40
  """
41
  if cls._logger is None:
42
  cls.setup_logging() # Ensure logging is set up before returning the logger
43
+ assert cls._logger is not None
44
  return cls._logger
src/telemetry/telemetry.py CHANGED
@@ -2,6 +2,7 @@
2
 
3
  import os
4
 
 
5
  from langfuse import Langfuse
6
  from langfuse.decorators import observe
7
 
@@ -9,32 +10,34 @@ from .logging_utils import Logger
9
 
10
  LOGGER = Logger.get_logger()
11
 
12
- tracer = None
13
 
14
-
15
- def init_telemetry() -> None:
16
  """Setup langfuse for tracing."""
17
- if os.getenv("USE_LANGFUSE", "false").lower() == "true":
18
- global tracer
19
- tracer = Langfuse(
20
- public_key=os.getenv("LANGFUSE_PUBLIC_KEY"),
21
- secret_key=os.getenv("LANGFUSE_SECRET_KEY"),
22
- host=os.getenv("LANGFUSE_HOST"),
23
- # otel_tracing_enabled=True,
24
- )
25
- assert tracer is not None, "Telemetry tracer not initialized"
26
- else:
27
- LOGGER.warning("Langfuse telemetry is disabled (USE_LANGFUSE != true)")
28
 
29
 
30
  @observe(name="📝 submit_feedback")
31
  def submit_feedback(rating: str, comment: str, trace_id: str) -> str:
 
 
 
 
 
 
 
 
32
  if not rating:
33
  return "⚠️ Please select a star rating before submitting."
34
 
35
  score = rating.count("⭐️") # Converts emoji to numeric
36
  stars_display = "⭐️" * score + "☆" * (5 - score)
37
-
38
  # Submit to Langfuse if trace_id is present
39
  if trace_id:
40
  try:
@@ -47,4 +50,7 @@ def submit_feedback(rating: str, comment: str, trace_id: str) -> str:
47
  except Exception as e:
48
  return f"✅ Feedback received ({stars_display}), but Langfuse logging failed: {e}"
49
 
50
- return f"✅ Thanks for your {stars_display} rating!{' Your comment: ' + comment if comment else ''}"
 
 
 
 
2
 
3
  import os
4
 
5
+ from functools import lru_cache
6
  from langfuse import Langfuse
7
  from langfuse.decorators import observe
8
 
 
10
 
11
  LOGGER = Logger.get_logger()
12
 
 
13
 
14
+ @lru_cache()
15
+ def init_telemetry() -> Langfuse:
16
  """Setup langfuse for tracing."""
17
+ # global TRACER
18
+ return Langfuse(
19
+ public_key=os.getenv("LANGFUSE_PUBLIC_KEY"),
20
+ secret_key=os.getenv("LANGFUSE_SECRET_KEY"),
21
+ host=os.getenv("LANGFUSE_HOST"),
22
+ )
 
 
 
 
 
23
 
24
 
25
  @observe(name="📝 submit_feedback")
26
  def submit_feedback(rating: str, comment: str, trace_id: str) -> str:
27
+ """Submit user feedback with a star rating and optional comment.
28
+ Args:
29
+ rating (str): Star rating as a string of emojis (e.g., "⭐⭐⭐").
30
+ comment (str): Optional user comment.
31
+ trace_id (str): Langfuse trace ID for linking feedback.
32
+ Returns:
33
+ str: Confirmation message indicating success or failure.
34
+ """
35
  if not rating:
36
  return "⚠️ Please select a star rating before submitting."
37
 
38
  score = rating.count("⭐️") # Converts emoji to numeric
39
  stars_display = "⭐️" * score + "☆" * (5 - score)
40
+ tracer = init_telemetry()
41
  # Submit to Langfuse if trace_id is present
42
  if trace_id:
43
  try:
 
50
  except Exception as e:
51
  return f"✅ Feedback received ({stars_display}), but Langfuse logging failed: {e}"
52
 
53
+ return (
54
+ f"✅ Thanks for your {stars_display} rating!"
55
+ f"{' Your comment: ' + comment if comment else ''}"
56
+ )