<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mulumba Kande Alexandre on Medium]]></title>
        <description><![CDATA[Stories by Mulumba Kande Alexandre on Medium]]></description>
        <link>https://medium.com/@kandealex007?source=rss-b1716ed1d671------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*gyF4BM2aWT7kYMgi0EEU4Q.jpeg</url>
            <title>Stories by Mulumba Kande Alexandre on Medium</title>
            <link>https://medium.com/@kandealex007?source=rss-b1716ed1d671------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 08:07:43 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kandealex007/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Building a Local AI-Powered Django ORM Studio — From Natural Language to Live Data]]></title>
            <link>https://medium.com/@kandealex007/building-a-local-ai-powered-django-orm-studio-from-natural-language-to-live-data-7dfaf6db953d?source=rss-b1716ed1d671------2</link>
            <guid isPermaLink="false">https://medium.com/p/7dfaf6db953d</guid>
            <dc:creator><![CDATA[Mulumba Kande Alexandre]]></dc:creator>
            <pubDate>Thu, 07 May 2026 09:18:44 GMT</pubDate>
            <atom:updated>2026-05-07T09:18:44.144Z</atom:updated>
            <content:encoded><![CDATA[<p>&gt; Ask a question in plain French. Get executable Django ORM code. Execute it. Then chat with your data — all running 100% locally, no API keys required.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*34hYnCwE4V4sh8UePArsXQ.png" /><figcaption>gemini</figcaption></figure><h3><strong>The Problem</strong></h3><p>Every Django developer has been there: you need a quick data check — “how many users signed up last week with at least one order?” — and instead of a 10-second answer, you spend five minutes constructing a QuerySet, running the shell, formatting the output. If you’re not the one who wrote the models, add another five minutes for `models.py` archaeology.</p><p>This project — <strong>**GenRequest**</strong> — solves that. You describe what you want in natural language, a local LLM generates the ORM code, the app executes it live against your database, and then you can <em>*talk*</em> to the results: ask follow-up questions, request new queries, and build up a shared context the LLM keeps referring to throughout the conversation.</p><p>Everything runs locally. The LLM is served by [Ollama](https://ollama.ai). No data leaves your machine.</p><h3><strong><em>## Stack</em></strong></h3><p><em>- </em><strong><em>**Django 4.2**</em></strong><em> — the app itself, SQLite in dev</em></p><p><em>- </em><strong><em>**Ollama + llama3.1:8b**</em></strong><em> — local LLM inference</em></p><p><em>- </em><strong><em>**Python 3.8**</em></strong><em>- No frontend framework — vanilla JS with the Fetch API</em></p><p><strong>— -</strong></p><h3><strong>## Architecture Overview</strong></h3><p>The app has three main phases that chain together:</p><pre>```<br>Natural language prompt<br>        ↓<br>  [LLM via Ollama]       ← streamed SSE response<br>        ↓<br>  Generated ORM code<br>        ↓<br>  [Execution pipeline]   ← preprocess → normalize → AST → exec/eval<br>        ↓<br>  Results (columns + rows)<br>        ↓<br>  [Multi-turn chat]      ← ollama.chat() with full context<br>```</pre><h3><strong>Part 1 — The RAG Layer: Auto-Synced Schema Context</strong></h3><p>The first clever piece is `generate_project_schema_context()` in `generator/generator/executor.py`. Every time the LLM is called, it receives a live description of every model in the project — fields, types, and foreign key relationships — introspected directly from the running Django app:</p><pre>from functools import lru_cache<br>from django.apps import apps<br>from django.db.models.fields.related import ForeignKey, ManyToManyField<br><br>_EXCLUDED_APP_LABELS = {&#39;auth&#39;, &#39;contenttypes&#39;, &#39;sessions&#39;, &#39;admin&#39;}<br><br>@lru_cache(maxsize=1)<br>def generate_project_schema_context() -&gt; str:<br>    lines = [&quot;Voici la structure exacte et exclusive des modèles Django disponibles :\n&quot;]<br><br>    for model in apps.get_models():<br>        if model._meta.app_label in _EXCLUDED_APP_LABELS:<br>            continue<br><br>        lines.append(f&quot;Modèle: {model.__name__}&quot;)<br>        lines.append(&quot;Champs disponibles :&quot;)<br><br>        for field in model._meta.get_fields():<br>            if not hasattr(field, &#39;verbose_name&#39;):<br>                continue<br>            field_type = field.get_internal_type()<br>            if isinstance(field, ForeignKey):<br>                target = field.remote_field.model.__name__<br>                lines.append(f&quot;  - {field.name} ({field_type}) -&gt; Clé étrangère vers &#39;{target}&#39;&quot;)<br>            elif isinstance(field, ManyToManyField):<br>                target = field.remote_field.model.__name__<br>                lines.append(f&quot;  - {field.name} ({field_type}) -&gt; ManyToMany avec &#39;{target}&#39;&quot;)<br>            else:<br>                lines.append(f&quot;  - {field.name} ({field_type})&quot;)<br>        lines.append(&quot;&quot;)<br><br>    return &quot;\n&quot;.join(lines)</pre><p>The `@lru_cache(maxsize=1)` means this only runs once per process lifetime. The result looks like:</p><pre>Modèle: Author<br>Champs disponibles :<br>  - id (AutoField)<br>  - name (CharField)<br><br>Modèle: Book<br>Champs disponibles :<br>  - id (AutoField)<br>  - title (CharField)<br>  - author (ForeignKey) -&gt; Clé étrangère vers &#39;Author&#39;</pre><p>This string goes verbatim into the system prompt. The LLM never hallucinates field names that don’t exist — because it’s only told about fields that <em>*do*</em> exist.</p><h3><strong>Part 2 — Streaming ORM Generation</strong></h3><p>Generation uses `ollama.generate()` with `stream=True` and sends chunks as [Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events):</p><pre>def stream_query_generation(request):<br>    dynamic_schema_context = generate_project_schema_context()<br><br>    model_names = &quot;, &quot;.join(<br>        m.__name__ for m in apps.get_models()<br>        if m._meta.app_label not in {&#39;auth&#39;, &#39;contenttypes&#39;, &#39;sessions&#39;, &#39;admin&#39;}<br>    )<br><br>    system_instruction = (<br>        &quot;Tu es un générateur de code Django ORM. Ton unique rôle est de produire du code Python exécutable.\n&quot;<br>        f&quot;{dynamic_schema_context}\n&quot;<br>        &quot;CONTEXTE D&#39;EXÉCUTION — ces noms sont déjà disponibles, n&#39;importe rien :\n&quot;<br>        f&quot;- Modèles : {model_names}\n&quot;<br>        &quot;- Helpers ORM : Q, F, Count, Sum, Avg, Max, Min, Value, Case, When, Subquery, OuterRef, Coalesce\n&quot;<br>        &quot;- Python : chain, groupby, combinations, defaultdict, Counter, sorted, zip, map, filter, any, all\n\n&quot;<br>        &quot;RÈGLES ABSOLUES :\n&quot;<br>        &quot;1. Renvoie UNIQUEMENT du code Python exécutable. Aucune phrase, aucune explication.\n&quot;<br>        &quot;2. Interdit : commentaires, imports, print(), markdown (```), texte en langage naturel.\n&quot;<br>        &quot;3. Référence les modèles directement par leur nom. Jamais model.Author ou models.Author.\n&quot;<br>        &quot;4. Relations ForeignKey : syntaxe double underscore (ex: author__name).\n&quot;<br>        &quot;5. La dernière ligne doit être l&#39;expression finale à évaluer.&quot;<br>    )<br><br>    def event_stream():<br>        start_time = time.time()<br>        full_response = &quot;&quot;<br>        response_stream = ollama.generate(<br>            model=&#39;llama3.1:8b&#39;,<br>            prompt=f&quot;{system_instruction}\n\nDemande utilisateur : {user_prompt}&quot;,<br>            stream=True,<br>        )<br>        for chunk in response_stream:<br>            text_chunk = chunk[&#39;response&#39;]<br>            full_response += text_chunk<br>            yield f&quot;data: {json.dumps({&#39;text&#39;: text_chunk})}\n\n&quot;<br><br>        duration = round(time.time() - start_time, 2)<br>        QueryHistory.objects.create(<br>            prompt_utilisateur=user_prompt,<br>            requete_generee=full_response.strip(),<br>            query_type=query_type,<br>            execution_time=duration,<br>        )<br>        yield f&quot;data: {json.dumps({&#39;status&#39;: &#39;DONE&#39;, &#39;duration&#39;: duration})}\n\n&quot;<br><br>    response = StreamingHttpResponse(event_stream(), content_type=&#39;text/event-stream&#39;)<br>    response[&#39;Cache-Control&#39;] = &#39;no-cache&#39;<br>    response[&#39;X-Accel-Buffering&#39;] = &#39;no&#39;  # disable Nginx buffering<br>    return response</pre><p>The frontend reads this stream with the Fetch API’s `ReadableStream`:</p><pre>const resp = await fetch(&quot;/stream-generation/&quot;, { method: &#39;POST&#39;, body: formData });<br>const reader = resp.body.getReader();<br>const dec = new TextDecoder(&#39;utf-8&#39;);<br>let buf = &#39;&#39;;<br><br>while (true) {<br>    const { value, done } = await reader.read();<br>    if (done) break;<br>    buf += dec.decode(value, { stream: true });<br>    const lines = buf.split(&#39;\n\n&#39;);<br>    buf = lines.pop();<br>    for (const line of lines) {<br>        if (!line.startsWith(&#39;data: &#39;)) continue;<br>        const data = JSON.parse(line.slice(6));<br>        if (data.text) {<br>            outputCode.textContent += data.text;<br>            Prism.highlightElement(outputCode); // syntax highlight as it streams<br>        }<br>        if (data.status === &#39;DONE&#39;) {<br>            metricsDiv.textContent = `Généré en ${data.duration}s via LLM local.`;<br>        }<br>    }<br>}</pre><p>The code appears token by token with live syntax highlighting. It feels fast even on a CPU-only machine because the user sees progress immediately.</p><h3><strong>Part 3 — The Execution Pipeline</strong></h3><p>This is the most technically interesting part. We can’t just `eval()` whatever the LLM returns — it generates imports (which require `__import__`), print statements, markdown fences, comments, and sometimes hallucinates `models.Author` instead of `Author`. We need a hardened pipeline.</p><p><strong>Step 1: Preprocessing</strong></p><pre>_IMPORT_RE = re.compile(r&#39;^\s*(import |from \S+ import )&#39;)<br>_PRINT_RE  = re.compile(r&#39;^\s*print\s*\(&#39;)<br>_COMMENT_RE = re.compile(r&#39;^\s*#&#39;)<br>_FENCE_RE  = re.compile(r&#39;^\s*```&#39;)<br><br>def _preprocess(code: str) -&gt; list:<br>    result = []<br>    for line in code.splitlines():<br>        stripped = line.strip()<br>        if not stripped:<br>            continue<br>        if (_IMPORT_RE.match(stripped) or _PRINT_RE.match(stripped)<br>                or _COMMENT_RE.match(stripped) or _FENCE_RE.match(stripped)):<br>            continue<br>        result.append(line.rstrip())  # preserve leading whitespace for for/if blocks<br>    return result</pre><p>Critical detail: we strip <em>*content*</em> but preserve <em>*indentation*</em>. An early version used `line.strip()` and completely broke `for` loops — their bodies lost their indent and Python raised `expected an indented block`.</p><p><strong>Step 2: Normalize LLM Hallucinations</strong></p><pre>preprocessed = re.sub(r&#39;\bmodels?\.&#39;, &#39;&#39;, preprocessed)</pre><p>One line. `\b` ensures `some_models.whatever` is untouched. This silently fixes `models.Author` → `Author` without stopping the user with an error.</p><p><strong>Step 3: Find the Result Expression with the AST</strong></p><p>Naive approaches — “take the last line”, “split on assignments” — break on multi-line chained queries like:</p><pre>Author.objects.annotate(<br>    nb_books=Count(&#39;book&#39;)<br>).values(&#39;name&#39;, &#39;nb_books&#39;)</pre><p>The solution is to use Python’s `ast` module:</p><pre>def _find_result_expr(code: str) -&gt; str:<br>    try:<br>        tree = ast.parse(code)<br>    except SyntaxError:<br>        return None<br><br>    if not tree.body:<br>        return None<br><br>    src_lines = code.splitlines()<br>    last = tree.body[-1]<br><br>    if isinstance(last, ast.Expr):<br>        # Multi-line expression: slice the exact source lines<br>        chunk = src_lines[last.lineno - 1:last.end_lineno]<br>        indent = len(chunk[0]) - len(chunk[0].lstrip())<br>        return &#39;\n&#39;.join(l[indent:] for l in chunk)<br><br>    # Walk back for the last assignment (handles for-loop patterns)<br>    for stmt in reversed(tree.body):<br>        if isinstance(stmt, ast.Assign) and isinstance(stmt.targets[-1], ast.Name):<br>            return stmt.targets[-1].id<br><br>    return None</pre><p>This correctly handles three patterns:</p><p>| Generated code | Result expression |</p><p>| — -| — -|</p><p>| `Author.objects.all()` | `Author.objects.all()` |</p><p>| `result = Author.objects.annotate(…)` | `result` |</p><p>| `books = []; for a in Author…; books` | `books` (last assignment) |</p><p><strong>Step 4: Secure exec() + eval()</strong></p><pre>_ORM_CONTEXT = {<br>    &#39;Q&#39;: Q, &#39;F&#39;: F, &#39;Count&#39;: Count, &#39;Sum&#39;: Sum, &#39;Avg&#39;: Avg,<br>    &#39;Max&#39;: Max, &#39;Min&#39;: Min, &#39;Value&#39;: Value, &#39;Subquery&#39;: Subquery,<br>    &#39;OuterRef&#39;: OuterRef, &#39;Case&#39;: Case, &#39;When&#39;: When,<br>    # stdlib — no import needed<br>    &#39;chain&#39;: chain, &#39;groupby&#39;: groupby, &#39;Counter&#39;: Counter, &#39;defaultdict&#39;: defaultdict,<br>    # ... etc<br>}<br><br>_SAFE_BUILTINS = {<br>    &#39;str&#39;: str, &#39;int&#39;: int, &#39;list&#39;: list, &#39;dict&#39;: dict, &#39;set&#39;: set,<br>    &#39;len&#39;: len, &#39;sorted&#39;: sorted, &#39;zip&#39;: zip, &#39;map&#39;: map, &#39;filter&#39;: filter,<br>    &#39;min&#39;: min, &#39;max&#39;: max, &#39;sum&#39;: sum, &#39;any&#39;: any, &#39;all&#39;: all,<br>    &#39;isinstance&#39;: isinstance, &#39;getattr&#39;: getattr,<br>    # notably absent: __import__, open, eval, exec, compile<br>}<br><br>context_globals = {model.__name__: model for model in apps.get_models()}<br>context_globals.update(_ORM_CONTEXT)<br>context_globals[&#39;__builtins__&#39;] = _SAFE_BUILTINS<br><br>exec(preprocessed, context_globals)<br>queryset = eval(result_expr, context_globals)</pre><p>Three security layers:</p><p>1. <strong>**String blocklist**</strong> — reject before exec if `__import__`, `os.`, `subprocess`, `eval(` etc. are present</p><p>2. <strong>**Restricted `__builtins__`**</strong> — no I/O, no import, no introspection escape hatches</p><p>3. <strong>**Model-name validation**</strong> — reject if no known model class name appears in the query</p><p><strong>Step 5: Adaptive Result Extraction</strong></p><p>A `ValuesQuerySet` (from `.values()`) has `hasattr(qs, ‘model’) == True` — but iterating it yields `dict` objects, not model instances. The old code assumed `.model` always meant instances and called `getattr(dict_obj, ‘id’)`, raising `KeyError: ‘id’`.</p><p>The fix: materialise with `list()` first, then branch on what you actually got:</p><pre>def _extract_result(queryset):<br>    if hasattr(queryset, &#39;model&#39;):<br>        items = list(queryset)<br>        if not items:<br>            return [f.name for f in queryset.model._meta.fields], []<br><br>        first = items[0]<br><br>        if isinstance(first, dict):            # .values()<br>            cols = list(first.keys())<br>            return cols, [[str(item.get(k, &#39;&#39;)) for k in cols] for item in items]<br><br>        if isinstance(first, (list, tuple)):   # .values_list()<br>            cols = [f&#39;col_{i+1}&#39; for i in range(len(first))]<br>            return cols, [[str(v) for v in row] for row in items]<br><br>        # regular model instances<br>        columns = [f.name for f in queryset.model._meta.fields]<br>        rows = []<br>        for obj in items:<br>            row = []<br>            for field in columns:<br>                val = getattr(obj, field)<br>                if hasattr(val, &#39;pk&#39;):<br>                    val = f&quot;{val.__class__.__name__} (ID: {val.pk})&quot;<br>                row.append(str(val) if val is not None else &quot;&quot;)<br>            rows.append(row)<br>        return columns, rows<br><br>    if isinstance(queryset, int):<br>        return [&#39;Résultat / Compte&#39;], [[str(queryset)]]<br><br>    if isinstance(queryset, dict):<br>        cols = list(queryset.keys())<br>        return cols, [[str(queryset[k]) for k in cols]]<br><br>    if isinstance(queryset, (list, tuple)) and queryset:<br>        first = queryset[0]<br>        if isinstance(first, dict):<br>            cols = list(first.keys())<br>            return cols, [[str(item.get(k, &#39;&#39;)) for k in cols] for item in queryset]<br>        if isinstance(first, (list, tuple)):<br>            cols = [f&#39;col_{i+1}&#39; for i in range(len(first))]<br>            return cols, [[str(v) for v in row] for row in queryset]<br><br>    return [&#39;Données&#39;], [[str(queryset)]]</pre><p><strong>Part 4 — The Chat Layer</strong></p><p>After the first execution the UI unlocks a chat zone. Every message is sent to `chat_with_data`, which uses `ollama.chat()` — the multi-turn API that accepts a messages array:</p><pre>def chat_with_data(request):<br>    history = json.loads(request.POST.get(&quot;history&quot;, &quot;[]&quot;))<br>    data_context = json.loads(request.POST.get(&quot;data_context&quot;, &quot;[]&quot;))<br><br>    schema_context = generate_project_schema_context()<br><br>    # Format executed results as plain tables for the LLM<br>    data_sections = []<br>    for i, ctx in enumerate(data_context[-5:]):  # cap at 5 most recent result sets<br>        label = ctx.get(&quot;query&quot;, f&quot;Résultat {i + 1}&quot;)<br>        header = &quot; | &quot;.join(ctx[&quot;columns&quot;])<br>        rows_str = &quot;\n&quot;.join(&quot; | &quot;.join(row) for row in ctx[&quot;rows&quot;][:50])<br>        data_sections.append(f&quot;[{label}]\n{header}\n{&#39;-&#39; * len(header)}\n{rows_str}&quot;)<br><br>    system_content = (<br>        &quot;Tu es un assistant expert Django ORM et analyse de données.\n\n&quot;<br>        f&quot;SCHÉMA DES MODÈLES :\n{schema_context}\n\n&quot;<br>        f&quot;DONNÉES DISPONIBLES :\n{chr(10).join(data_sections)}\n\n&quot;<br>        &quot;RÈGLES :\n&quot;<br>        &quot;- Réponds en français, de façon concise et précise.\n&quot;<br>        &quot;- Appuie-toi sur les données disponibles.\n&quot;<br>        &quot;- Si tu proposes du code Django ORM, entoure-le de ```python ... ```.\n&quot;<br>        &quot;- Si une question nécessite des données absentes, propose une requête ORM.&quot;<br>    )<br><br>    messages = [{&quot;role&quot;: &quot;system&quot;, &quot;content&quot;: system_content}]<br>    for msg in history[-10:]:   # cap at 10 turns to control context size<br>        messages.append({&quot;role&quot;: msg[&quot;role&quot;], &quot;content&quot;: msg[&quot;content&quot;]})<br>    messages.append({&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: message})<br><br>    def event_stream():<br>        stream = ollama.chat(model=&#39;llama3.1:8b&#39;, messages=messages, stream=True)<br>        for chunk in stream:<br>            yield f&quot;data: {json.dumps({&#39;text&#39;: chunk[&#39;message&#39;][&#39;content&#39;]})}\n\n&quot;<br>        yield f&quot;data: {json.dumps({&#39;status&#39;: &#39;DONE&#39;})}\n\n&quot;<br><br>    response = StreamingHttpResponse(event_stream(), content_type=&#39;text/event-stream&#39;)<br>    response[&#39;Cache-Control&#39;] = &#39;no-cache&#39;<br>    return response</pre><p>Key design choices:</p><p>- <strong>**Last 5 result sets, 50 rows each**</strong> — keeps the context window from exploding on large datasets</p><p>- <strong>**Last 10 conversation turns**</strong> — enough for coherent follow-ups without ballooning the prompt</p><p>- <strong>**`ollama.chat()` instead of `ollama.generate()`**</strong> — the messages array keeps conversation state server-side; the client just appends new turns</p><p><strong>Inline Code Blocks in Chat</strong></p><p>When the LLM suggests a new query in chat, the response contains a ` ```python ``` ` block. The frontend parses these <em>*after*</em> the stream ends and attaches an Execute button:</p><pre>function renderAssistantContent(text) {<br>    const root = document.createElement(&#39;div&#39;);<br>    const parts = text.split(/(```python[\s\S]*?```)/g);<br><br>    parts.forEach(part =&gt; {<br>        if (part.startsWith(&#39;```python&#39;)) {<br>            const code = part.replace(/^```python\n?/, &#39;&#39;).replace(/\n?```$/, &#39;&#39;).trim();<br>            const wrap = document.createElement(&#39;div&#39;);<br>            wrap.innerHTML = `&lt;pre&gt;&lt;code class=&quot;language-python&quot;&gt;${esc(code)}&lt;/code&gt;&lt;/pre&gt;`;<br>            const btn = document.createElement(&#39;button&#39;);<br>            btn.textContent = &#39;⚡ Exécuter dans Django&#39;;<br>            btn.addEventListener(&#39;click&#39;, () =&gt; executeChatCode(code, btn));<br>            wrap.appendChild(btn);<br>            root.appendChild(wrap);<br>        } else {<br>            part.trim().split(&#39;\n&#39;).forEach(line =&gt; {<br>                if (!line.trim()) return;<br>                const p = document.createElement(&#39;p&#39;);<br>                p.textContent = line;<br>                root.appendChild(p);<br>            });<br>        }<br>    });<br>    return root;<br>}</pre><p>Clicking Execute posts to the same `/execute-query/` endpoint, appends the results as a new chat bubble, and pushes them into `state.dataContext` so the LLM references them in all future turns.</p><h3><strong>Part 5 — Client State Management</strong></h3><p>The entire frontend state lives in two arrays:</p><pre>const state = {<br>    history: [],     // [{role, content}] — sent to /chat/ on every message<br>    dataContext: [], // [{query, columns, rows}] — all executed results<br>};</pre><p>After each execution, `state.dataContext` grows:</p><pre>// In the execute-btn handler, after a successful execution:<br>state.dataContext.push({<br>    query: code.substring(0, 80),<br>    columns: data.columns,<br>    rows: data.rows,<br>});<br>document.getElementById(&#39;chat-zone&#39;).style.display = &#39;block&#39;;</pre><p>After each chat turn, `state.history` grows:</p><pre>state.history.push({ role: &#39;user&#39;, content: text });<br>// ... stream response ...<br>state.history.push({ role: &#39;assistant&#39;, content: fullText });</pre><p>Both are serialised to JSON and sent with every chat request. The LLM always has full context.</p><h3><strong>Models</strong></h3><pre>class QueryHistory(models.Model):<br>    schema = models.ForeignKey(DatabaseSchema, on_delete=models.SET_NULL, null=True)<br>    prompt_utilisateur = models.TextField()<br>    requete_generee = models.TextField(blank=True, null=True)<br>    query_type = models.CharField(max_length=50)<br>    execution_time = models.FloatField(null=True)<br>    is_helpful = models.BooleanField(null=True)  # thumbs up/down feedback<br>    created_at = models.DateTimeField(auto_now_add=True)<br><br>    class Meta:<br>        ordering = [&#39;-created_at&#39;]</pre><p>Every generation is persistent—duration, the prompt, and the generated code. The sidebar shows the last 10. The `is_helpful`field feeds back into the voting endpoint (`/vote/&lt;id&gt;/`).</p><h3><strong>Running It</strong></h3><pre># 1. Pull the model<br>ollama pull llama3.1:8b<br><br># 2. Clone and install<br>git clone https://github.com/alexandre00007/GenRequest.git<br>cd GenRequest<br>pip install -r requirements.txt<br><br># 3. Configure<br>cp .env.example .env<br># Edit .env: set SECRET_KEY at minimum<br><br># 4. Migrate and run<br>python manage.py migrate<br>python manage.py runserver</pre><p>Open `http://127.0.0.1:8000`. Describe what you want. Execute. Chat.</p><h3><strong>What I Learned</strong></h3><p><strong>**Prompt engineering beats post-processing — but you need both.**</strong> The system prompt tells the LLM what’s available and what’s forbidden. But LLMs are probabilistic: they’ll still occasionally write `models.Author`. The `re.sub(r’\bmodels?\.’, ‘’, code)` normalization is the silent safety net.</p><p><strong>**`ast.parse` is the right tool for understanding generated code.**</strong> Regex on Python source is fragile. The AST tells you exactly what the last statement <em>*is*</em> — expression, assignment, or control flow — and gives you line numbers to slice the original source for multi-line expressions.</p><p><strong>**Preserve indentation when preprocessing.**</strong> Every line-based preprocessor that calls `line.strip()` will break any generated code that uses `for`, `if`, or `with` blocks. Strip the <em>*content*</em> of unwanted lines, not the whitespace of the ones you keep.</p><p><strong>**Materialise querysets before inspecting them.**</strong> `ValuesQuerySet` has a `.model` attribute but yields dicts. Calling `list(queryset)` first and branching on `isinstance(first, dict)` is the only reliable way to handle all queryset variants uniformly.</p><p><strong>**SSE + StreamingHttpResponse is surprisingly straightforward in Django.**</strong> No WebSockets, no Channels, no async — just a generator function yielding `data: …\n\n` lines. Disable Nginx buffering with `X-Accel-Buffering: no` and it works end-to-end.</p><h3><strong>What’s Next</strong></h3><p>- <strong>**Multi-schema support**</strong> — `DatabaseSchema` is already in the models; wiring it to the UI would let you switch between projects</p><p>- <strong>**Model picker**</strong> — instead of injecting the entire schema, let the user select which models are in scope for this session</p><p>- <strong>**Export**</strong> — download results as CSV directly from the table</p><p>- <strong>**Persistent chat sessions**</strong> — store conversation history in the DB so you can resume where you left off</p><p><em>*The full source is on GitHub: [alexandre00007/GenRequest](</em>https://github.com/alexandre00007/GenRequest<em>)*</em></p><p><em>*Stack: Django 4.2 · Ollama · llama3.1:8b · Python 3.8 · SQLite · vanilla JS*</em></p><p>Thanks…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7dfaf6db953d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building a Robust Payroll Processing System in Python: Automating Deduplication, Summaries, and…]]></title>
            <link>https://medium.com/@kandealex007/building-a-robust-payroll-processing-system-in-python-automating-deduplication-summaries-and-66dec6c57b46?source=rss-b1716ed1d671------2</link>
            <guid isPermaLink="false">https://medium.com/p/66dec6c57b46</guid>
            <category><![CDATA[enhancing-payroll-data]]></category>
            <category><![CDATA[automating-payroll]]></category>
            <category><![CDATA[payroll-processing-system]]></category>
            <category><![CDATA[optimizing-large-scale]]></category>
            <dc:creator><![CDATA[Mulumba Kande Alexandre]]></dc:creator>
            <pubDate>Tue, 05 Aug 2025 14:25:42 GMT</pubDate>
            <atom:updated>2025-08-05T14:25:42.432Z</atom:updated>
            <content:encoded><![CDATA[<h3>Building a Robust Payroll Processing System in Python: Automating Deduplication, Summaries, and Reporting</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*a79UdxeSvDVovGe8uKEnWQ.png" /></figure><h3>Introduction</h3><p>In the world of payroll management, accuracy and efficiency are paramount. Imagine dealing with large datasets from databases and Excel files, identifying duplicates, calculating financial impacts, and generating comprehensive reports — all while ensuring data integrity across multiple sources. This is the challenge I tackled in a recent project: developing a Python script for processing payroll data from an Access database and declarative Excel files.</p><p>This article dives into the details of this “huge work” — a state-of-the-art payroll processing tool built with Python. We’ll explore its architecture, key features, and how it solves real-world problems like duplicate detection, summary metrics, and report generation. I’ll walk you through the code implementation step by step, explaining each function’s purpose, inputs, outputs, and logic. Whether you’re a developer, data analyst, or HR professional, this script demonstrates how automation can streamline complex workflows. The code is modular, extensible, and designed for scalability, making it a valuable starting point for similar projects.</p><p>The full code is provided below, broken down into sections with explanations. You can copy and adapt it for your needs.</p><h3>The Problem: Chaos in Payroll Data</h3><p>Payroll processing often involves reconciling data from disparate sources:<br>- **Listing Data**: From an Access database (e.g., Microsoft Access .accdb files), containing detailed employee records like matricule (ID), names, salaries, and allowances.<br>- **Declarative Data**: From Excel files, listing declared employees, which may have mismatches or duplicates.</p><p>Common issues include:<br>- Duplicates based on IDs or names, leading to overpayments or errors.<br>- Missing or invalid IDs (e.g., “NU” or blank).<br>- Cross-section payments (employees paid in other sections).<br>- Need for summaries (e.g., total salary impact) and comparisons (declared vs. paid).<br>- Generating a consolidated Excel report with annexes for detailed data.</p><p>Manual handling is error-prone and time-consuming. The goal was to automate this: fetch data, clean it, deduplicate, compute metrics, and output a report with all annexes in one file.</p><h3>The Solution: A Python Script for Payroll Automation</h3><p>The script is built around several key functions, using libraries like Pandas for data manipulation, PyODBC for database connections, Openpyxl for Excel handling, and Tqdm for progress tracking. It’s structured to create directories, process data, deduplicate, and generate reports.</p><h4>Step 1: Import Necessary Libraries</h4><p>We start with imports for all required modules. This sets up the environment for data handling, logging, and Excel operations.</p><pre>import os<br>import logging<br>import shutil<br>from typing import List, Optional, Union, Dict<br>import pandas as pd<br>import pyodbc<br>import openpyxl<br>from datetime import datetime<br>from tqdm import tqdm<br>import string<br>import re<br>from openpyxl.utils.dataframe import dataframe_to_rows<br></pre><h4>Step 2: Directory Setup Function</h4><p>The `<em>setup_directory_structure</em>` function creates organized folders for inputs, outputs, and reports. It supports timestamping and force recreation for clean runs.</p><pre>def setup_directory_structure(ministry: str, base_path: str = &quot;.&quot;, force_recreate: bool = False, add_timestamp: bool = False) -&gt; List[str]:<br>    &quot;&quot;&quot;<br>    Create a base directory structure for a given ministry and return the created paths.<br><br>    Parameters:<br>    - ministry (str): Name of the ministry to include in the directory structure.<br>    - base_path (str): Base path where the directory structure will be created. Default: current directory.<br>    - force_recreate (bool): If True, delete existing directories and recreate them. Default: False.<br>    - add_timestamp (bool): If True, append a timestamp to the base directory name. Default: False.<br><br>    Returns:<br>    - List[str]: List of created or existing directory paths.<br>    &quot;&quot;&quot;<br>    logging.basicConfig(<br>        level=logging.INFO,<br>        format=&quot;%(asctime)s - %(levelname)s - %(message)s&quot;,<br>        handlers=[logging.StreamHandler()]<br>    )<br>    logger = logging.getLogger(__name__)<br><br>    timestamp = datetime.now().strftime(&quot;%Y%m%d_%H%M%S&quot;) if add_timestamp else &quot;&quot;<br>    base_dir = f&quot;TRAITEMENT{ministry}{timestamp}&quot; if timestamp else f&quot;TRAITEMENT{ministry}&quot;<br><br>    directories = [<br>        base_dir,<br>        os.path.join(base_dir, &quot;LISTINGPAIE&quot;),<br>        os.path.join(base_dir, &quot;DECLARATION&quot;),<br>        os.path.join(base_dir, &quot;FINAL&quot;),<br>        os.path.join(base_dir, &quot;LISTINGPAIE&quot;, &quot;FICHIERDEPART&quot;),<br>        os.path.join(base_dir, &quot;DECLARATION&quot;, &quot;FICHIERDEPART&quot;),<br>        os.path.join(base_dir, &quot;REPORTS&quot;)<br>    ]<br><br>    created_paths = []<br><br>    try:<br>        for directory in directories:<br>            full_path = os.path.join(base_path, directory)<br>            if force_recreate and os.path.exists(full_path):<br>                shutil.rmtree(full_path)<br>                logger.info(f&quot;Deleted existing directory: {full_path}&quot;)<br>            if not os.path.exists(full_path):<br>                os.makedirs(full_path, exist_ok=True)<br>                logger.info(f&quot;Directory created successfully: {full_path}&quot;)<br>            else:<br>                logger.info(f&quot;Directory already exists: {full_path}&quot;)<br>            created_paths.append(full_path)<br><br>        return created_paths<br><br>    except OSError as e:<br>        logger.error(f&quot;Error creating directory structure: {e}&quot;)<br>        raise</pre><p>This function ensures all outputs are neatly organized, preventing clutter in your working directory.</p><h4>Step 3: Custom Results Directory</h4><p>`<em>create_custom_results_directory</em>` creates a subfolder for results based on data stats (original, unique, duplicates rows), helping track different runs.</p><pre>def create_custom_results_directory(base_dir: str, summary: dict) -&gt; str:<br>    &quot;&quot;&quot;<br>    Create a customized results directory based on the processing summary.<br><br>    Parameters:<br>    - base_dir (str): The base directory under which to create the custom results dir.<br>    - summary (dict): The summary dictionary from data processing.<br><br>    Returns:<br>    - str: Path to the created custom results directory.<br>    &quot;&quot;&quot;<br>    logger = logging.getLogger(__name__)<br>    custom_dir_name = f&quot;RESULTS_O{summary[&#39;original_rows&#39;]}_U{summary[&#39;unique_rows&#39;]}_D{summary[&#39;duplicates_saved&#39;]}&quot;<br>    results_dir = os.path.join(base_dir, custom_dir_name)<br><br>    try:<br>        if not os.path.exists(results_dir):<br>            os.makedirs(results_dir, exist_ok=True)<br>            logger.info(f&quot;Custom results directory created: {results_dir}&quot;)<br>        else:<br>            logger.info(f&quot;Custom results directory already exists: {results_dir}&quot;)<br>        return results_dir<br>    except OSError as e:<br>        logger.error(f&quot;Error creating custom results directory: {e}&quot;)<br>        raise</pre><h4>Step 4: Summary Metrics Calculation</h4><p>`<em>calculate_summary_metrics</em>` computes financial sums from payroll columns, crucial for impact assessment.</p><pre>def calculate_summary_metrics(data: pd.DataFrame) -&gt; Dict[str, float]:<br>    &quot;&quot;&quot;<br>    Calculate summary metrics for a DataFrame.<br><br>    Parameters:<br>    - data (pd.DataFrame): The DataFrame to summarize.<br><br>    Returns:<br>    - Dict[str, float]: Dictionary with calculated sums.<br>    &quot;&quot;&quot;<br>    metrics = {<br>        &quot;somme_salaire_base&quot;: data[&quot;Base&quot;].sum() if &quot;Base&quot; in data.columns else 0.0,<br>        &quot;somme_transport&quot;: data[&quot;Transport&quot;].sum() if &quot;Transport&quot; in data.columns else 0.0,<br>        &quot;somme_Prime&quot;: data[&quot;Prime&quot;].sum() if &quot;Prime&quot; in data.columns else 0.0,<br>        &quot;somme_Logement&quot;: data[&quot;Logement&quot;].sum() if &quot;Logement&quot; in data.columns else 0.0,<br>        &quot;somme_MontantNet&quot;: data[&quot;MontantNet&quot;].sum() if &quot;MontantNet&quot; in data.columns else 0.0,<br>        &quot;somme_Pension_Rente&quot;: data[&quot;Pension_Rente&quot;].sum() if &quot;Pension_Rente&quot; in data.columns else 0.0<br>    }<br>    metrics[&quot;sum&quot;] = metrics[&quot;somme_salaire_base&quot;] + metrics[&quot;somme_transport&quot;] + metrics[&quot;somme_Prime&quot;] + metrics[&quot;somme_Logement&quot;] + metrics[&quot;somme_Pension_Rente&quot;]<br>    return metrics</pre><h4>Step 5: Saving Global Summaries</h4><p>`<em>save_global_summary</em>` outputs metrics to Excel (or CSV/JSON), with sheets for each dataset.</p><pre>def save_global_summary(global_summaries: Dict[str, Dict[str, float]], output_path: str, output_format: str = &quot;xlsx&quot;):<br>    &quot;&quot;&quot;<br>    Save all summaries to a global summary file.<br><br>    Parameters:<br>    - global_summaries (Dict[str, Dict[str, float]]): Dictionary of file names and their summary metrics.<br>    - output_path (str): Path to save the global summary file.<br>    - output_format (str): Output file format (&#39;xlsx&#39;, &#39;csv&#39;, &#39;json&#39;). Default: &#39;xlsx&#39;.<br>    &quot;&quot;&quot;<br>    logger = logging.getLogger(__name__)<br>    try:<br>        if output_format == &quot;xlsx&quot;:<br>            wb = openpyxl.Workbook()<br>            wb.remove(wb.active)  # Remove default sheet<br>            for file_name, metrics in global_summaries.items():<br>                ws = wb.create_sheet(title=file_name[:31])  # Excel sheet names limited to 31 characters<br>                ws.append([&quot;Metric&quot;, &quot;Value&quot;])<br>                for metric, value in metrics.items():<br>                    ws.append([metric, value])<br>            wb.save(output_path)<br>        elif output_format == &quot;csv&quot;:<br>            summary_df = pd.DataFrame(global_summaries).T<br>            summary_df.to_csv(output_path, encoding=&#39;utf-8&#39;)<br>        elif output_format == &quot;json&quot;:<br>            with open(output_path, &#39;w&#39;, encoding=&#39;utf-8&#39;) as f:<br>                pd.DataFrame(global_summaries).T.to_json(f, orient=&#39;index&#39;)<br>        logger.info(f&quot;Global summary saved to: {output_path}&quot;)<br>    except Exception as e:<br>        logger.error(f&quot;Error saving global summary: {e}&quot;)<br>        raise</pre><h4>Step 6: Report Generation</h4><p>`<em>generate_excel_report</em>` builds the consolidated “rapport.xlsx”, with a main sheet for summaries and annex sheets for details.</p><pre>def generate_excel_report(summaries_listing: Dict, global_summaries_listing: Dict, summaries_decl: Dict, global_summaries_decl: Dict, comparisons: Dict, report_path: str, section: str, trimestre: str, annee: int, annex_paths: Optional[Dict[str, str]] = None, output_format: str = &quot;xlsx&quot;):<br>    &quot;&quot;&quot;<br>    Generate an Excel report for both listing and declarative, including comparisons.<br><br>    Parameters:<br>    - summaries_listing (Dict): Summaries for listing.<br>    - global_summaries_listing (Dict): Global summaries for listing.<br>    - summaries_decl (Dict): Summaries for declarative.<br>    - global_summaries_decl (Dict): Global summaries for declarative.<br>    - comparisons (Dict): Comparison metrics.<br>    - report_path (str): Path to save the report.<br>    - section (str): The section name.<br>    - trimestre (str): The trimester.<br>    - annee (int): The year.<br>    - annex_paths (Dict[str, str], optional): Dictionary of annex names to their paths.<br>    - output_format (str): Output file format (&#39;xlsx&#39;, &#39;csv&#39;, &#39;json&#39;). Default: &#39;xlsx&#39;.<br>    &quot;&quot;&quot;<br>    logger = logging.getLogger(__name__)<br>    wb = openpyxl.Workbook()<br>    ws = wb.active<br>    ws.title = &quot;Rapport&quot;<br><br>    headers = [&quot;Categories&quot;, &quot;Enregistrement&quot;, &quot;Concernés&quot;, &quot;Impact&quot;, &quot;Annexe&quot;]<br><br>    current_row = 1<br><br>    ws.cell(row=current_row, column=1, value=&quot;Liste Déclarative&quot;)<br>    current_row += 1<br>    for i, header in enumerate(headers, 1):<br>        ws.cell(row=current_row, column=i, value=header)<br>    current_row += 1<br><br>    data_to_declaratif = [<br>        [&quot;Effectif total déclaré &quot;, summaries_decl.get(&quot;donnees_rows&quot;, 0), summaries_decl.get(&quot;donnees_rows&quot;, 0), global_summaries_decl.get(&quot;donnees&quot;, {}).get(&quot;sum&quot;, 0), f&quot;donnees_decl_{section}.xlsx&quot;],<br>        [&quot;Doublons par matricule ou Matricules partagés &quot;, summaries_decl.get(&quot;matricule_mod&quot;, {}).get(&quot;duplicates_saved&quot;, 0), summaries_decl.get(&quot;matricule_mod&quot;, {}).get(&quot;unique_duplicates_saved&quot;, 0), global_summaries_decl.get(&quot;duplicates_by_matricule_mod_decl&quot;, {}).get(&quot;sum&quot;, 0), &quot;duplicates_by_matricule_mod_decl.xlsx&quot;],<br>        [&quot;Doublons par noms &quot;, summaries_decl.get(&quot;nomscompact&quot;, {}).get(&quot;duplicates_saved&quot;, 0), summaries_decl.get(&quot;nomscompact&quot;, {}).get(&quot;unique_duplicates_saved&quot;, 0), global_summaries_decl.get(&quot;duplicates_by_nomscompact_decl&quot;, {}).get(&quot;sum&quot;, 0), &quot;duplicates_by_nomscompact_decl.xlsx&quot;],<br>        [&quot;Effectif déclaré NU &quot;, summaries_decl.get(&quot;missing_matricule_mod_rows&quot;, 0), summaries_decl.get(&quot;missing_matricule_mod_unique_rows&quot;, 0), global_summaries_decl.get(&quot;missing_matricule_mod&quot;, {}).get(&quot;sum&quot;, 0), &quot;missing_matricule_mod_decl.xlsx&quot;],<br>    ]<br><br>    for row in data_to_declaratif:<br>        for c, value in enumerate(row, 1):<br>            ws.cell(row=current_row, column=c, value=value)<br>        current_row += 1<br>    current_row += 2<br><br>    ws.cell(row=current_row, column=1, value=&quot;Fichier Listing de Paie&quot;)<br>    current_row += 1<br>    for i, header in enumerate(headers, 1):<br>        ws.cell(row=current_row, column=i, value=header)<br>    current_row += 1<br><br>    data_to_listing = [<br>        [&quot;Effectif total pris en charge sur le fichier-listing du Ministère du Budget  &quot;, summaries_listing.get(&quot;donnees_rows&quot;, 0), summaries_listing.get(&quot;donnees_rows&quot;, 0), global_summaries_listing.get(&quot;donnees&quot;, {}).get(&quot;sum&quot;, 0), f&quot;donnees_{section}.xlsx&quot;],<br>        [&quot;Effectif NU &quot;, summaries_listing.get(&quot;missing_matricule_mod_rows&quot;, 0), summaries_listing.get(&quot;missing_matricule_mod_unique_rows&quot;, 0), global_summaries_listing.get(&quot;missing_matricule_mod&quot;, {}).get(&quot;sum&quot;, 0), &quot;missing_matricule_mod.xlsx&quot;],<br>        [&quot;Doublons par matricule ou matricules partagés  &quot;, summaries_listing.get(&quot;matricule_mod&quot;, {}).get(&quot;duplicates_saved&quot;, 0), summaries_listing.get(&quot;matricule_mod&quot;, {}).get(&quot;unique_duplicates_saved&quot;, 0), global_summaries_listing.get(&quot;duplicates_by_matricule_mod&quot;, {}).get(&quot;sum&quot;, 0) - global_summaries_listing.get(&quot;duplicates_by_matricule_modunique&quot;, {}).get(&quot;sum&quot;, 0), &quot;duplicates_by_matricule_mod.xlsx&quot;],<br>        [&quot;Doublons par noms &quot;, summaries_listing.get(&quot;nomscompact&quot;, {}).get(&quot;duplicates_saved&quot;, 0), summaries_listing.get(&quot;nomscompact&quot;, {}).get(&quot;unique_duplicates_saved&quot;, 0), global_summaries_listing.get(&quot;duplicates_by_nomscompact&quot;, {}).get(&quot;sum&quot;, 0) - global_summaries_listing.get(&quot;duplicates_by_nomscompactunique&quot;, {}).get(&quot;sum&quot;, 0), &quot;duplicates_by_nomscompact.xlsx&quot;],<br>        [&quot;Agents payés ailleurs par nom &quot;, summaries_listing.get(&quot;nomscompact&quot;, {}).get(&quot;agents_in_other_sections_filtered&quot;, 0), summaries_listing.get(&quot;nomscompact&quot;, {}).get(&quot;agents_in_other_sections_filtered_unique&quot;, 0), global_summaries_listing.get(&quot;agents_in_other_sections_by_nomscompact&quot;, {}).get(&quot;sum&quot;, 0) - global_summaries_listing.get(&quot;agents_in_other_sections_by_nomscompact_unique&quot;, {}).get(&quot;sum&quot;, 0), &quot;agents_in_other_sections_by_nomscompact.xlsx&quot;],<br>        [&quot;Agents payés ailleurs par matricule  &quot;, summaries_listing.get(&quot;matricule_mod&quot;, {}).get(&quot;agents_in_other_sections_filtered&quot;, 0), summaries_listing.get(&quot;matricule_mod&quot;, {}).get(&quot;agents_in_other_sections_filtered_unique&quot;, 0), global_summaries_listing.get(&quot;agents_in_other_sections_by_matricule_mod&quot;, {}).get(&quot;sum&quot;, 0) - global_summaries_listing.get(&quot;agents_in_other_sections_by_matricule_mod_unique&quot;, {}).get(&quot;sum&quot;, 0), &quot;agents_in_other_sections_by_matricule_mod.xlsx&quot;],<br>    ]<br><br>    for row in data_to_listing:<br>        for c, value in enumerate(row, 1):<br>            ws.cell(row=current_row, column=c, value=value)<br>        current_row += 1<br>    current_row += 2<br><br>    ws.cell(row=current_row, column=1, value=&quot;Comparaisons&quot;)<br>    current_row += 1<br>    for i, header in enumerate(headers, 1):<br>        ws.cell(row=current_row, column=i, value=header)<br>    current_row += 1<br><br>    data_to_comp = [<br>        [&quot;Agents déclarés mais payés dans d&#39;autres sections par matricule&quot;, comparisons.get(&quot;declared_paid_other_by_matricule_records&quot;, 0), comparisons.get(&quot;declared_paid_other_by_matricule&quot;, 0), comparisons.get(&quot;sum_declared_paid_other_by_matricule&quot;, 0) - comparisons.get(&quot;sum_declared_paid_other_by_matricule_unique&quot;, 0), &quot;declared_paid_other_by_matricule.xlsx&quot;],<br>        [&quot;Agents déclarés mais payés dans d&#39;autres sections par nom&quot;, comparisons.get(&quot;declared_paid_other_by_nomscompact_records&quot;, 0), comparisons.get(&quot;declared_paid_other_by_nomscompact&quot;, 0), comparisons.get(&quot;sum_declared_paid_other_by_nomscompact&quot;, 0) - comparisons.get(&quot;sum_declared_paid_other_by_nomscompact_unique&quot;, 0), &quot;declared_paid_other_by_nomscompact.xlsx&quot;],<br>        [&quot;Agents déclarés et présents dans le listing par matricule&quot;, comparisons.get(&quot;declared_in_listing_by_matricule_records&quot;, 0), comparisons.get(&quot;declared_in_listing_by_matricule&quot;, 0), comparisons.get(&quot;sum_declared_in_listing_by_matricule&quot;, 0) - comparisons.get(&quot;sum_declared_in_listing_by_matricule_unique&quot;, 0), &quot;declared_in_listing_by_matricule.xlsx&quot;],<br>        [&quot;Agents déclarés et présents dans le listing par nom&quot;, comparisons.get(&quot;declared_in_listing_by_nomscompact_records&quot;, 0), comparisons.get(&quot;declared_in_listing_by_nomscompact&quot;, 0), comparisons.get(&quot;sum_declared_in_listing_by_nomscompact&quot;, 0) - comparisons.get(&quot;sum_declared_in_listing_by_nomscompact_unique&quot;, 0), &quot;declared_in_listing_by_nomscompact.xlsx&quot;],<br>        [&quot;Agents non déclarés mais payés dans la section par matricule&quot;, comparisons.get(&quot;non_declared_paid_section_by_matricule_records&quot;, 0), comparisons.get(&quot;non_declared_paid_section_by_matricule&quot;, 0), comparisons.get(&quot;sum_non_declared_paid_section_by_matricule&quot;, 0) - comparisons.get(&quot;sum_non_declared_paid_section_by_matricule_unique&quot;, 0), &quot;non_declared_paid_section_by_matricule.xlsx&quot;],<br>        [&quot;Agents non déclarés mais payés dans la section par nom&quot;, comparisons.get(&quot;non_declared_paid_section_by_nomscompact_records&quot;, 0), comparisons.get(&quot;non_declared_paid_section_by_nomscompact&quot;, 0), comparisons.get(&quot;sum_non_declared_paid_section_by_nomscompact&quot;, 0) - comparisons.get(&quot;sum_non_declared_paid_section_by_nomscompact_unique&quot;, 0), &quot;non_declared_paid_section_by_nomscompact.xlsx&quot;],<br>    ]<br><br>    for row in data_to_comp:<br>        for c, value in enumerate(row, 1):<br>            ws.cell(row=current_row, column=c, value=value)<br>        current_row += 1<br>    current_row += 2<br><br>    ws.cell(row=current_row, column=1, value=f&#39;NB: le traitement est fait sur le fichier du listing et declarative {trimestre} de l\&#39;année {annee}.&#39;)<br><br>    if annex_paths:<br>        for annex_name, path in annex_paths.items():<br>            if path and os.path.exists(path):<br>                try:<br>                    if annex_name.endswith(&#39;.xlsx&#39;):<br>                        df = pd.read_excel(path)<br>                    elif annex_name.endswith(&#39;.csv&#39;):<br>                        df = pd.read_csv(path, encoding=&#39;utf-8&#39;)<br>                    elif annex_name.endswith(&#39;.json&#39;):<br>                        df = pd.read_json(path, orient=&#39;records&#39;)<br>                    else:<br>                        logger.warning(f&quot;Unsupported file format for annex {annex_name}&quot;)<br>                        continue<br>                    sheet_title = annex_name.replace(&#39;.xlsx&#39;, &#39;&#39;)[:31]<br>                    # Ensure unique sheet title by appending a number if necessary<br>                    base_title = sheet_title<br>                    suffix = 1<br>                    while sheet_title in wb.sheetnames:<br>                        sheet_title = f&quot;{base_title[:29]}{suffix}&quot;[:31]<br>                        suffix += 1<br>                    ws_annex = wb.create_sheet(title=sheet_title)<br>                    for r in dataframe_to_rows(df, index=False, header=True):<br>                        ws_annex.append(r)<br>                    logger.info(f&quot;Added annex sheet for {annex_name}&quot;)<br>                except Exception as e:<br>                    logger.error(f&quot;Error loading annex {annex_name}: {e}&quot;)<br><br>    wb.save(report_path)<br>    logger.info(f&quot;Excel report saved to: {report_path}&quot;)<br><br>def remove_duplicates_excel(<br>    data: pd.DataFrame,<br>    column: str,<br>    results_dir: str,<br>    output_format: str = &quot;xlsx&quot;,<br>    case_sensitive: bool = True,<br>    excluded_values: Optional[List[Union[str, int]]] = None,<br>    generate_unique_duplicates: bool = False,<br>    prefix: str = &quot;&quot;<br>) -&gt; dict:<br>    &quot;&quot;&quot;<br>    Remove duplicates based on a single column and save unique and all duplicate rows.<br>    Optionally generate a file with unique rows from duplicates.<br><br>    Parameters:<br>    - data (pd.DataFrame): The DataFrame to process.<br>    - column (str): The column to check for duplicates.<br>    - results_dir (str): Directory to save the output files.<br>    - output_format (str): Output file format (&#39;xlsx&#39;, &#39;csv&#39;, &#39;json&#39;). Default: &#39;xlsx&#39;.<br>    - case_sensitive (bool): Whether to perform case-sensitive comparison (default: True).<br>    - excluded_values (List[str, int], optional): Values to exclude from the column.<br>    - generate_unique_duplicates (bool): If True, generate a file with unique rows from duplicates. Default: False.<br>    - prefix (str): Prefix for the file names. Default: &#39;&#39;.<br><br>    Returns:<br>    - dict: Summary statistics (original rows, unique rows, duplicates saved, unique duplicates saved).<br>    &quot;&quot;&quot;<br>    logger = logging.getLogger(__name__)<br>    default_excluded_values = [<br>        &quot;&quot;, &quot;nu&quot;, &quot;Nu&quot;, &quot;uN&quot;, &quot;NU&quot;, &quot;nan&quot;, &quot;NaN&quot;, &quot;naN&quot;, &quot;Nan&quot;, &quot;NAN&quot;,<br>        &quot;nAn&quot;, &quot;Nat&quot;, &quot;naT&quot;, &quot;NaT&quot;, &quot;nAt&quot;, &quot;0&quot;, &quot;00&quot;, &quot;000&quot;, &quot;0000&quot;,<br>        &quot;00000&quot;, &quot;000000&quot;, &quot;0000000&quot;<br>    ]<br>    excluded_values = excluded_values if excluded_values is not None else default_excluded_values<br><br>    output_format = &#39;xlsx&#39; if output_format.lower() == &#39;excel&#39; else output_format.lower()<br>    if output_format not in [&quot;xlsx&quot;, &quot;csv&quot;, &quot;json&quot;]:<br>        raise ValueError(f&quot;Unsupported output format: {output_format}&quot;)<br><br>    try:<br>        data = data.copy()<br>        data[column] = data[column].astype(str).str.strip()<br>        if not case_sensitive:<br>            data[column] = data[column].str.lower()<br><br>        if excluded_values:<br>            logger.info(f&quot;Filtering out excluded values for {column}: {excluded_values}&quot;)<br>            data = data[~data[column].isin(excluded_values)]<br><br>        original_row_count = len(data)<br>        value_counts = data[column].value_counts()<br>        duplicate_values = value_counts[value_counts &gt; 1].index<br>        duplicates_mask = data[column].isin(duplicate_values)<br>        duplicates_data = data[duplicates_mask]<br>        unique_data = data.drop_duplicates(subset=column, keep=&quot;first&quot;)<br><br>        unique_row_count = len(unique_data)<br>        duplicates_saved = len(duplicates_data)<br>        unique_duplicates_data = duplicates_data.drop_duplicates(subset=column, keep=&quot;first&quot;) if generate_unique_duplicates and duplicates_saved &gt; 0 else pd.DataFrame()<br>        unique_duplicates_saved = len(unique_duplicates_data)<br><br>        summary = {<br>            &quot;original_rows&quot;: original_row_count,<br>            &quot;unique_rows&quot;: unique_row_count,<br>            &quot;duplicates_saved&quot;: duplicates_saved,<br>            &quot;unique_duplicates_saved&quot;: unique_duplicates_saved<br>        }<br><br>        logger.info(f&quot;Summary for {column}: {summary}&quot;)<br><br>        unique_path = os.path.join(results_dir, f&quot;unique_by_{column}{prefix}.{output_format}&quot;)<br>        duplicates_path = os.path.join(results_dir, f&quot;duplicates_by_{column}{prefix}.{output_format}&quot;)<br>        unique_duplicates_path = os.path.join(results_dir, f&quot;duplicates_by_{column}{prefix}unique.{output_format}&quot;) if generate_unique_duplicates and duplicates_saved &gt; 0 else None<br><br>        if output_format == &quot;xlsx&quot;:<br>            unique_data.to_excel(unique_path, index=False, engine=&#39;openpyxl&#39;)<br>            if duplicates_saved &gt; 0:<br>                duplicates_data.to_excel(duplicates_path, index=False, engine=&#39;openpyxl&#39;)<br>            if unique_duplicates_path:<br>                unique_duplicates_data.to_excel(unique_duplicates_path, index=False, engine=&#39;openpyxl&#39;)<br>        elif output_format == &quot;csv&quot;:<br>            unique_data.to_csv(unique_path, index=False, encoding=&#39;utf-8&#39;)<br>            if duplicates_saved &gt; 0:<br>                duplicates_data.to_csv(duplicates_path, index=False, encoding=&#39;utf-8&#39;)<br>            if unique_duplicates_path:<br>                unique_duplicates_data.to_csv(unique_duplicates_path, index=False, encoding=&#39;utf-8&#39;)<br>        elif output_format == &quot;json&quot;:<br>            unique_data.to_json(unique_path, orient=&#39;records&#39;, lines=True)<br>            if duplicates_saved &gt; 0:<br>                duplicates_data.to_json(duplicates_path, orient=&#39;records&#39;, lines=True)<br>            if unique_duplicates_path:<br>                unique_duplicates_data.to_json(unique_duplicates_path, orient=&#39;records&#39;, lines=True)<br><br>        logger.info(f&quot;Unique data by {column} saved to: {unique_path}&quot;)<br>        if duplicates_saved &gt; 0:<br>            logger.info(f&quot;All duplicate rows by {column} saved to: {duplicates_path}&quot;)<br>        else:<br>            logger.info(f&quot;No duplicates found for {column}.&quot;)<br>        if unique_duplicates_path:<br>            logger.info(f&quot;Unique duplicates by {column} saved to: {unique_duplicates_path}&quot;)<br><br>        # Calculate summary metrics for each file<br>        file_summaries = {<br>            f&quot;unique_by_{column}{prefix}&quot;: calculate_summary_metrics(unique_data),<br>            f&quot;duplicates_by_{column}{prefix}&quot;: calculate_summary_metrics(duplicates_data) if duplicates_saved &gt; 0 else {},<br>            f&quot;duplicates_by_{column}{prefix}unique&quot;: calculate_summary_metrics(unique_duplicates_data) if unique_duplicates_path else {}<br>        }<br><br>        return {<br>            &quot;summary&quot;: summary,<br>            &quot;file_paths&quot;: {<br>                &quot;unique&quot;: unique_path,<br>                &quot;duplicates&quot;: duplicates_path if duplicates_saved &gt; 0 else None,<br>                &quot;unique_duplicates&quot;: unique_duplicates_path<br>            },<br>            &quot;file_summaries&quot;: file_summaries<br>        }<br><br>    except Exception as e:<br>        logger.error(f&quot;An error occurred during deduplication for {column}: {e}&quot;)<br>        raise<br><br>def process_access_data(<br>    db_path: str,<br>    table_name: str,<br>    section: str,<br>    categorie: Optional[str] = None,<br>    unite_affectation: Optional[str] = None,<br>    output_columns: Optional[List[str]] = None,<br>    output_format: str = &quot;xlsx&quot;,<br>    ministry: str = &quot;DEFAULT&quot;,<br>    base_path: str = &quot;.&quot;,<br>    filter_query: Optional[str] = None,<br>    filter_conditions: Optional[Dict[str, Union[str, List[str]]]] = None,<br>    deduplicate_columns: Optional[List[str]] = None,<br>    case_sensitive: bool = True,<br>    projection_columns: Optional[List[str]] = None<br>) -&gt; Dict[str, Union[str, dict]]:<br>    &quot;&quot;&quot;<br>    Query data from an Access database, process it, save to a file, and perform deduplication by matricule_mod and nomscompact.<br>    Generate files for agents paid in the specified section and other sections by matricule_mod and nomscompact.<br>    Create a global summary file with metrics for each generated file.<br><br>    Parameters:<br>    - db_path (str): Path to the Access database file.<br>    - table_name (str): Name of the table to query.<br>    - section (str): Section filter for the query (e.g., &#39;tourisme&#39;).<br>    - categorie (str, optional): Categorie filter for the query.<br>    - unite_affectation (str, optional): UniteAffectation filter for the query.<br>    - output_columns (List[str], optional): Columns to include in the output file. Default: all columns.<br>    - output_format (str): Output file format (&#39;xlsx&#39;, &#39;csv&#39;, &#39;json&#39;). Default: &#39;xlsx&#39;.<br>    - ministry (str): Name of the ministry for directory structure. Default: &#39;DEFAULT&#39;.<br>    - base_path (str): Base path for directory structure. Default: current directory.<br>    - filter_query (str, optional): Pandas query string for post-processing filtering.<br>    - filter_conditions (Dict[str, Union[str, List[str]]], optional): Dictionary of column filters.<br>    - deduplicate_columns (List[str], optional): Columns to deduplicate on (e.g., [&#39;matricule_mod&#39;, &#39;nomscompact&#39;]).<br>    - case_sensitive (bool): Whether deduplication is case-sensitive. Default: True.<br>    - projection_columns (List[str], optional): Columns to include in the projection file.<br><br>    Returns:<br>    - dict: Contains paths to output files, projection file, and processing summaries.<br>    &quot;&quot;&quot;<br>    logger = logging.getLogger(__name__)<br>    punctuation = re.escape(string.punctuation)<br>    output_format = &#39;xlsx&#39; if output_format.lower() == &#39;excel&#39; else output_format.lower()<br>    if output_format not in [&quot;xlsx&quot;, &quot;csv&quot;, &quot;json&quot;]:<br>        raise ValueError(f&quot;Unsupported output format: {output_format}&quot;)<br><br>    try:<br>        # Setup directory structure<br>        created_dirs = setup_directory_structure(ministry, base_path, add_timestamp=True)<br>        base_dir = created_dirs[0]<br>        reports_dir = created_dirs[-1]<br>        final_dir = created_dirs[3]<br><br>        # Initialize global summaries<br>        global_summaries = {}<br><br>        # Initialize summaries<br>        summaries = {&quot;donnees_rows&quot;: 0, &quot;missing_matricule_mod_rows&quot;: 0, &quot;missing_matricule_mod_unique_rows&quot;: 0}<br><br>        # Connect to Access database<br>        conn_str = f&quot;Driver={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ={db_path};&quot;<br>        conn = pyodbc.connect(conn_str, uid=&quot;&quot;, pwd=&quot;&quot;)<br>        cursor = conn.cursor()<br><br>        # Build SQL query for initial data<br>        query_conditions = [f&quot;Section LIKE &#39;%{section}%&#39;&quot;, &quot;Categorie &lt;&gt; &#39;BUDGETS ANNEXES&#39;&quot;]<br>        if categorie:<br>            query_conditions.append(f&quot;Categorie LIKE &#39;%{categorie}%&#39;&quot;)<br>        if unite_affectation:<br>            query_conditions.append(f&quot;UniteAffectation LIKE &#39;%{unite_affectation}%&#39;&quot;)<br>        query = f&quot;SELECT * FROM {table_name} WHERE {&#39; AND &#39;.join(query_conditions)}&quot;<br>        logger.info(f&quot;Executing query for {section}: {query}&quot;)<br>        cursor.execute(query)<br>        rows = cursor.fetchall()<br>        columns = [col[0] for col in cursor.description]<br><br>        # Convert to DataFrame<br>        data = pd.DataFrame([tuple(row) for row in tqdm(rows, desc=&quot;Processing rows&quot;)], columns=columns)<br>        logger.info(f&quot;Fetched {len(data)} rows from {table_name} for section {section}&quot;)<br><br>        # Apply dictionary-based column filters<br>        original_row_count = len(data)<br>        filtered_out_rows = pd.DataFrame(columns=data.columns)<br>        if filter_conditions:<br>            logger.info(f&quot;Applying column filters: {filter_conditions}&quot;)<br>            for col, condition in filter_conditions.items():<br>                if col not in data.columns:<br>                    raise ValueError(f&quot;Filter column &#39;{col}&#39; not found in the DataFrame.&quot;)<br>                if isinstance(condition, str):<br>                    mask = data[col].astype(str).str.contains(condition, case=False, regex=True, na=False)<br>                else:<br>                    mask = data[col].astype(str).str.contains(&#39;|&#39;.join(condition), case=False, regex=True, na=False)<br>                filtered_out_rows = pd.concat([filtered_out_rows, data[~mask]], ignore_index=True)<br>                data = data[mask]<br>            logger.info(f&quot;Rows after column filters: {len(data)}&quot;)<br><br>        # Apply post-processing filter if provided<br>        if filter_query:<br>            logger.info(f&quot;Applying post-processing filter: {filter_query}&quot;)<br>            filtered_out_rows = pd.concat([filtered_out_rows, data.query(f&quot;~({filter_query})&quot;, engine=&#39;python&#39;)], ignore_index=True)<br>            data = data.query(filter_query, engine=&#39;python&#39;).copy()<br><br>        # Update summaries with processed data rows<br>        summaries[&quot;donnees_rows&quot;] = len(data)<br><br>        # Data cleaning<br>        data.loc[:, &quot;NomPostnom&quot;] = data[&quot;NomPostnom&quot;].astype(str).str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br>        data.loc[:, &quot;Prenom&quot;] = data[&quot;Prenom&quot;].astype(str).str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br>        data.loc[:, &quot;nomscompact&quot;] = data[&quot;NomPostnom&quot;].str.cat(data[&quot;Prenom&quot;], sep=&quot;&quot;).str.upper()<br>        data.loc[:, &quot;matricule_mod&quot;] = data[&quot;Matricule&quot;].astype(str).str.upper().str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br><br>        # Validate output columns<br>        if output_columns:<br>            invalid_cols = [col for col in output_columns if col not in data.columns]<br>            if invalid_cols:<br>                raise ValueError(f&quot;Invalid output columns: {invalid_cols}&quot;)<br>        else:<br>            output_columns = data.columns.tolist()<br><br>        # Extract and save missing matricule_mod<br>        excluded_values = [&quot;&quot;, &quot;nu&quot;, &quot;Nu&quot;, &quot;uN&quot;, &quot;NU&quot;, &quot;nan&quot;, &quot;NaN&quot;, &quot;naN&quot;, &quot;Nan&quot;, &quot;NAN&quot;, &quot;nAn&quot;, &quot;Nat&quot;, &quot;naT&quot;, &quot;NaT&quot;, &quot;nAt&quot;, &quot;0&quot;, &quot;00&quot;, &quot;000&quot;, &quot;0000&quot;, &quot;00000&quot;, &quot;000000&quot;, &quot;0000000&quot;]<br>        missing_matricule_mod = data[data[&quot;matricule_mod&quot;].isin(excluded_values)]<br>        missing_path = os.path.join(reports_dir, f&quot;missing_matricule_mod.{output_format}&quot;)<br>        if not missing_matricule_mod.empty:<br>            if output_format == &quot;xlsx&quot;:<br>                missing_matricule_mod.to_excel(missing_path, index=False, engine=&#39;openpyxl&#39;)<br>            elif output_format == &quot;csv&quot;:<br>                missing_matricule_mod.to_csv(missing_path, index=False, encoding=&#39;utf-8&#39;)<br>            elif output_format == &quot;json&quot;:<br>                missing_matricule_mod.to_json(missing_path, orient=&#39;records&#39;, lines=True)<br>            logger.info(f&quot;Missing matricule_mod rows ({len(missing_matricule_mod)}) saved to: {missing_path}&quot;)<br>            global_summaries[&quot;missing_matricule_mod&quot;] = calculate_summary_metrics(missing_matricule_mod)<br>            # Add unique for missing<br>            unique_missing = missing_matricule_mod.drop_duplicates(subset=&quot;nomscompact&quot;, keep=&quot;first&quot;)<br>            unique_missing_path = os.path.join(reports_dir, f&quot;missing_matricule_mod_unique.{output_format}&quot;)<br>            if output_format == &quot;xlsx&quot;:<br>                unique_missing.to_excel(unique_missing_path, index=False, engine=&#39;openpyxl&#39;)<br>            elif output_format == &quot;csv&quot;:<br>                unique_missing.to_csv(unique_missing_path, index=False, encoding=&#39;utf-8&#39;)<br>            elif output_format == &quot;json&quot;:<br>                unique_missing.to_json(unique_missing_path, orient=&#39;records&#39;, lines=True)<br>            logger.info(f&quot;Unique missing matricule_mod saved to: {unique_missing_path}&quot;)<br>            global_summaries[&quot;missing_matricule_mod_unique&quot;] = calculate_summary_metrics(unique_missing)<br>            summaries[&quot;missing_matricule_mod_rows&quot;] = len(missing_matricule_mod)<br>            summaries[&quot;missing_matricule_mod_unique_rows&quot;] = len(unique_missing)<br>        else:<br>            logger.info(f&quot;No missing matricule_mod rows found.&quot;)<br>            summaries[&quot;missing_matricule_mod_rows&quot;] = 0<br>            summaries[&quot;missing_matricule_mod_unique_rows&quot;] = 0<br><br>        # Save validation report for other excluded rows<br>        excluded_rows = filtered_out_rows.drop_duplicates()<br>        validation_report_path = None<br>        if not excluded_rows.empty:<br>            validation_report_path = os.path.join(reports_dir, f&quot;validation_report_{section}.{output_format}&quot;)<br>            if output_format == &quot;xlsx&quot;:<br>                wb = openpyxl.Workbook()<br>                sheet = wb.active<br>                sheet.title = &quot;Excluded Rows&quot;<br>                summary_sheet = wb.create_sheet(&quot;Summary&quot;)<br>                summary_sheet.append([&quot;Metric&quot;, &quot;Count&quot;])<br>                summary_sheet.append([&quot;Total Excluded Rows&quot;, len(excluded_rows)])<br>                summary_sheet.append([&quot;Invalid nomscompact/matricule_mod&quot;, len(data[data[&quot;nomscompact&quot;].isin([&quot;&quot;, &quot;nan&quot;, &quot;NaN&quot;]) | data[&quot;matricule_mod&quot;].isin([&quot;&quot;, &quot;nan&quot;, &quot;NaN&quot;])])])<br>                summary_sheet.append([&quot;Filtered Out by Conditions&quot;, len(filtered_out_rows)])<br>                sheet.append(output_columns + [&quot;matricule_mod&quot;, &quot;nomscompact&quot;])<br>                for row in excluded_rows[output_columns + [&quot;matricule_mod&quot;, &quot;nomscompact&quot;]].itertuples(index=False):<br>                    sheet.append(row)<br>                wb.save(validation_report_path)<br>            elif output_format == &quot;csv&quot;:<br>                excluded_rows.to_csv(validation_report_path, index=False, encoding=&#39;utf-8&#39;)<br>            elif output_format == &quot;json&quot;:<br>                excluded_rows.to_json(validation_report_path, orient=&#39;records&#39;, lines=True)<br>            logger.info(f&quot;Validation report saved to: {validation_report_path}&quot;)<br>            global_summaries[&quot;validation_report&quot;] = calculate_summary_metrics(excluded_rows)<br><br>        # Save projection if requested<br>        projection_path = None<br>        if projection_columns:<br>            invalid_cols = [col for col in projection_columns if col not in data.columns]<br>            if invalid_cols:<br>                raise ValueError(f&quot;Invalid projection columns: {invalid_cols}&quot;)<br>            projection_path = os.path.join(reports_dir, f&quot;projection_{section}.{output_format}&quot;)<br>            projection_data = data[projection_columns]<br>            if output_format == &quot;xlsx&quot;:<br>                projection_data.to_excel(projection_path, index=False, engine=&#39;openpyxl&#39;)<br>            elif output_format == &quot;csv&quot;:<br>                projection_data.to_csv(projection_path, index=False, encoding=&#39;utf-8&#39;)<br>            elif output_format == &quot;json&quot;:<br>                projection_data.to_json(projection_path, orient=&#39;records&#39;, lines=True)<br>            logger.info(f&quot;Projection saved to: {projection_path}&quot;)<br>            global_summaries[&quot;projection&quot;] = calculate_summary_metrics(projection_data)<br><br>        # Save initial output<br>        initial_output_path = os.path.join(final_dir, f&quot;donnees_{section}.{output_format}&quot;)<br>        if output_format == &quot;xlsx&quot;:<br>            wb = openpyxl.Workbook()<br>            sheet = wb.active<br>            sheet.title = &quot;Les données à Traiter Filtrage&quot;<br>            summary_sheet = wb.create_sheet(&quot;Summary&quot;)<br>            summary_sheet.append([&quot;Rubrique&quot;, &quot;Nombre&quot;])<br>            summary_sheet.append([&quot;Les données à Traiter Filtrage&quot;, len(data)])<br>            summary_sheet.append([&quot;Original Rows (Pre-Filter)&quot;, original_row_count])<br>            sheet.append(output_columns + [&quot;matricule_mod&quot;, &quot;nomscompact&quot;])<br>            for row in tqdm(data[output_columns + [&quot;matricule_mod&quot;, &quot;nomscompact&quot;]].itertuples(index=False), desc=&quot;Writing to Excel&quot;):<br>                sheet.append(row)<br>            wb.save(initial_output_path)<br>        else:<br>            data[output_columns + [&quot;matricule_mod&quot;, &quot;nomscompact&quot;]].to_csv(initial_output_path, index=False, encoding=&#39;utf-8&#39;) if output_format == &quot;csv&quot; else data.to_json(initial_output_path, orient=&#39;records&#39;, lines=True)<br>        logger.info(f&quot;Initial data saved to: {initial_output_path}&quot;)<br>        global_summaries[&quot;donnees&quot;] = calculate_summary_metrics(data)<br><br>        # Backup initial output<br>        backup_path = os.path.join(final_dir, f&quot;backup_donnees_{section}_{datetime.now().strftime(&#39;%Y%m%d_%H%M%S&#39;)}.{output_format}&quot;)<br>        shutil.copy(initial_output_path, backup_path)<br>        logger.info(f&quot;Backup created: {backup_path}&quot;)<br><br>        # Deduplicate by matricule_mod and nomscompact separately if requested<br>        results_dir = None<br>        if deduplicate_columns:<br>            results_dir = create_custom_results_directory(base_dir, {&quot;original_rows&quot;: len(data), &quot;unique_rows&quot;: len(data), &quot;duplicates_saved&quot;: 0})<br>            for col in deduplicate_columns:<br>                generate_unique = col in [&quot;matricule_mod&quot;, &quot;nomscompact&quot;]  # Generate unique duplicates for both<br>                result = remove_duplicates_excel(<br>                    data=data,<br>                    column=col,<br>                    results_dir=results_dir,<br>                    output_format=output_format,<br>                    case_sensitive=case_sensitive,<br>                    generate_unique_duplicates=generate_unique,<br>                    prefix=&quot;&quot;<br>                )<br>                summaries[col] = result[&quot;summary&quot;]<br>                summaries[col][&quot;file_paths&quot;] = result[&quot;file_paths&quot;]<br>                global_summaries.update(result[&quot;file_summaries&quot;])<br><br>        # Find agents in other sections<br>        agents_in_other_sections = {&quot;matricule_mod&quot;: None, &quot;nomscompact&quot;: None}<br>        agents_in_other_sections_paths = {&quot;matricule_mod&quot;: None, &quot;nomscompact&quot;: None}<br>        agents_in_other_sections_unique_paths = {&quot;matricule_mod&quot;: None, &quot;nomscompact&quot;: None}<br>        if results_dir and deduplicate_columns:<br>            # Extract unique matricule_mod and nomscompact from donnees_{section}.xlsx<br>            section_data = pd.read_excel(initial_output_path, sheet_name=&quot;Les données à Traiter Filtrage&quot;) if output_format == &quot;xlsx&quot; else pd.read_csv(initial_output_path) if output_format == &quot;csv&quot; else pd.read_json(initial_output_path)<br>            unique_matricule_mod = [x for x in section_data[&quot;matricule_mod&quot;].unique() if x not in excluded_values]<br>            unique_nomscompact = [x for x in section_data[&quot;nomscompact&quot;].unique() if x not in excluded_values]<br><br>            # Query database for other sections<br>            conn = pyodbc.connect(conn_str, uid=&quot;&quot;, pwd=&quot;&quot;)<br>            cursor = conn.cursor()<br><br>            # Query for other sections (with Base &gt; 0 for paid)<br>            query_other_sections = f&quot;SELECT * FROM {table_name} WHERE Section NOT LIKE &#39;%{section}%&#39; AND Categorie &lt;&gt; &#39;BUDGETS ANNEXES&#39; AND Base &gt; 0&quot;<br>            cursor.execute(query_other_sections)<br>            rows = cursor.fetchall()<br>            other_sections_data = pd.DataFrame([tuple(row) for row in tqdm(rows, desc=&quot;Processing other sections&quot;)], columns=columns)<br><br>            if not other_sections_data.empty:<br>                # Clean nomscompact and matricule_mod<br>                other_sections_data.loc[:, &quot;NomPostnom&quot;] = other_sections_data[&quot;NomPostnom&quot;].astype(str).str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br>                other_sections_data.loc[:, &quot;Prenom&quot;] = other_sections_data[&quot;Prenom&quot;].astype(str).str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br>                other_sections_data.loc[:, &quot;nomscompact&quot;] = other_sections_data[&quot;NomPostnom&quot;].str.cat(other_sections_data[&quot;Prenom&quot;], sep=&quot;&quot;).str.upper()<br>                other_sections_data.loc[:, &quot;matricule_mod&quot;] = other_sections_data[&quot;Matricule&quot;].astype(str).str.upper().str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br><br>            # For matricule_mod<br>            if &quot;matricule_mod&quot; in deduplicate_columns and unique_matricule_mod:<br>                other_sections_data_matricule = other_sections_data[other_sections_data[&quot;matricule_mod&quot;].isin(unique_matricule_mod)] if not other_sections_data.empty else pd.DataFrame()<br>                agents_in_other_sections[&quot;matricule_mod&quot;] = other_sections_data_matricule<br>                summaries[&quot;matricule_mod&quot;][&quot;agents_in_other_sections_filtered&quot;] = len(other_sections_data_matricule)<br>                summaries[&quot;matricule_mod&quot;][&quot;agents_in_other_sections_filtered_unique&quot;] = len(other_sections_data_matricule.drop_duplicates(subset=&quot;matricule_mod&quot;)) if not other_sections_data_matricule.empty else 0<br><br>            # For nomscompact<br>            if &quot;nomscompact&quot; in deduplicate_columns and unique_nomscompact:<br>                other_sections_data_nomscompact = other_sections_data[other_sections_data[&quot;nomscompact&quot;].isin(unique_nomscompact)] if not other_sections_data.empty else pd.DataFrame()<br>                agents_in_other_sections[&quot;nomscompact&quot;] = other_sections_data_nomscompact<br>                summaries[&quot;nomscompact&quot;][&quot;agents_in_other_sections_filtered&quot;] = len(other_sections_data_nomscompact)<br>                summaries[&quot;nomscompact&quot;][&quot;agents_in_other_sections_filtered_unique&quot;] = len(other_sections_data_nomscompact.drop_duplicates(subset=&quot;nomscompact&quot;)) if not other_sections_data_nomscompact.empty else 0<br><br>            cursor.close()<br>            conn.close()<br><br>        # Save agents in other sections<br>        if results_dir and deduplicate_columns:<br>            for col in deduplicate_columns:<br>                if agents_in_other_sections[col] is not None and not agents_in_other_sections[col].empty:<br>                    path = os.path.join(results_dir, f&quot;agents_in_other_sections_by_{col}.{output_format}&quot;)<br>                    filtered_data = agents_in_other_sections[col]<br>                    if output_format == &quot;xlsx&quot;:<br>                        filtered_data.to_excel(path, index=False, engine=&#39;openpyxl&#39;)<br>                    elif output_format == &quot;csv&quot;:<br>                        filtered_data.to_csv(path, index=False, encoding=&#39;utf-8&#39;)<br>                    elif output_format == &quot;json&quot;:<br>                        filtered_data.to_json(path, orient=&#39;records&#39;, lines=True)<br>                    logger.info(f&quot;Agents in other sections by {col} (Base &gt; 0) saved to: {path}&quot;)<br>                    agents_in_other_sections_paths[col] = path<br>                    global_summaries[f&quot;agents_in_other_sections_by_{col}&quot;] = calculate_summary_metrics(filtered_data)<br><br>                    # Generate unique from filtered data<br>                    unique_filtered_data = filtered_data.drop_duplicates(subset=col, keep=&quot;first&quot;)<br>                    filtered_unique_path = os.path.join(results_dir, f&quot;agents_in_other_sections_by_{col}_unique.{output_format}&quot;)<br>                    if not unique_filtered_data.empty:<br>                        if output_format == &quot;xlsx&quot;:<br>                            unique_filtered_data.to_excel(filtered_unique_path, index=False, engine=&#39;openpyxl&#39;)<br>                        elif output_format == &quot;csv&quot;:<br>                            unique_filtered_data.to_csv(filtered_unique_path, index=False, encoding=&#39;utf-8&#39;)<br>                        elif output_format == &quot;json&quot;:<br>                            unique_filtered_data.to_json(filtered_unique_path, orient=&#39;records&#39;, lines=True)<br>                        logger.info(f&quot;Unique filtered agents in other sections by {col} saved to: {filtered_unique_path}&quot;)<br>                        global_summaries[f&quot;agents_in_other_sections_by_{col}_unique&quot;] = calculate_summary_metrics(unique_filtered_data)<br>                    agents_in_other_sections_unique_paths[col] = filtered_unique_path if not unique_filtered_data.empty else None<br>                else:<br>                    summaries[col][&quot;agents_in_other_sections_filtered&quot;] = 0<br>                    summaries[col][&quot;agents_in_other_sections_filtered_unique&quot;] = 0<br><br>        # Save global summary<br>        global_summary_path = os.path.join(reports_dir, f&quot;global_summary_listing.{output_format}&quot;)<br>        save_global_summary(global_summaries, global_summary_path, output_format)<br><br>        return {<br>            &quot;initial_output_path&quot;: initial_output_path,<br>            &quot;backup_path&quot;: backup_path,<br>            &quot;missing_matricule_mod_path&quot;: missing_path if not missing_matricule_mod.empty else None,<br>            &quot;missing_matricule_mod_unique_path&quot;: unique_missing_path if &#39;unique_missing_path&#39; in locals() else None,<br>            &quot;validation_report_path&quot;: validation_report_path if not excluded_rows.empty else None,<br>            &quot;projection_path&quot;: projection_path if projection_columns else None,<br>            &quot;global_summary_path&quot;: global_summary_path,<br>            &quot;summaries&quot;: summaries,<br>            &quot;unique_by_matricule_mod_path&quot;: summaries.get(&quot;matricule_mod&quot;, {}).get(&quot;file_paths&quot;, {}).get(&quot;unique&quot;) if deduplicate_columns and &quot;matricule_mod&quot; in deduplicate_columns else None,<br>            &quot;duplicates_by_matricule_mod_path&quot;: summaries.get(&quot;matricule_mod&quot;, {}).get(&quot;file_paths&quot;, {}).get(&quot;duplicates&quot;) if deduplicate_columns and &quot;matricule_mod&quot; in deduplicate_columns else None,<br>            &quot;unique_duplicates_by_matricule_mod_path&quot;: summaries.get(&quot;matricule_mod&quot;, {}).get(&quot;file_paths&quot;, {}).get(&quot;unique_duplicates&quot;) if deduplicate_columns and &quot;matricule_mod&quot; in deduplicate_columns and summaries.get(&quot;matricule_mod&quot;, {}).get(&quot;duplicates_saved&quot;, 0) &gt; 0 else None,<br>            &quot;unique_by_nomscompact_path&quot;: summaries.get(&quot;nomscompact&quot;, {}).get(&quot;file_paths&quot;, {}).get(&quot;unique&quot;) if deduplicate_columns and &quot;nomscompact&quot; in deduplicate_columns else None,<br>            &quot;duplicates_by_nomscompact_path&quot;: summaries.get(&quot;nomscompact&quot;, {}).get(&quot;file_paths&quot;, {}).get(&quot;duplicates&quot;) if deduplicate_columns and &quot;nomscompact&quot; in deduplicate_columns else None,<br>            &quot;unique_duplicates_by_nomscompact_path&quot;: summaries.get(&quot;nomscompact&quot;, {}).get(&quot;file_paths&quot;, {}).get(&quot;unique_duplicates&quot;) if deduplicate_columns and &quot;nomscompact&quot; in deduplicate_columns and summaries.get(&quot;nomscompact&quot;, {}).get(&quot;duplicates_saved&quot;, 0) &gt; 0 else None,<br>            &quot;agents_in_other_sections_by_matricule_mod_filtered_path&quot;: agents_in_other_sections_paths.get(&quot;matricule_mod&quot;),<br>            &quot;agents_in_other_sections_by_nomscompact_filtered_path&quot;: agents_in_other_sections_paths.get(&quot;nomscompact&quot;),<br>            &quot;agents_in_other_sections_by_matricule_mod_filtered_unique_path&quot;: agents_in_other_sections_unique_paths.get(&quot;matricule_mod&quot;),<br>            &quot;agents_in_other_sections_by_nomscompact_filtered_unique_path&quot;: agents_in_other_sections_unique_paths.get(&quot;nomscompact&quot;),<br>            &quot;data&quot;: data,  # Return the processed data for further use<br>            &quot;global_summaries&quot;: global_summaries<br>        }<br><br>    except Exception as e:<br>        logger.error(f&quot;Error processing data: {e}&quot;)<br>        raise<br><br>def process_excel_declarative(<br>    excel_path: str,<br>    db_path: str,<br>    table_name: str,<br>    section: str,<br>    output_columns: Optional[List[str]] = None,<br>    output_format: str = &quot;xlsx&quot;,<br>    ministry: str = &quot;DEFAULT&quot;,<br>    base_path: str = &quot;.&quot;,<br>    filter_query: Optional[str] = None,<br>    filter_conditions: Optional[Dict[str, Union[str, List[str]]]] = None,<br>    deduplicate_columns: Optional[List[str]] = None,<br>    case_sensitive: bool = True,<br>    projection_columns: Optional[List[str]] = None,<br>    listing_data: pd.DataFrame = None<br>) -&gt; Dict[str, Union[str, dict]]:<br>    &quot;&quot;&quot;<br>    Process the declarative list from an Excel file, perform deduplication, and compare with listing data from database.<br><br>    Parameters:<br>    - excel_path (str): Path to the Excel file for declarative list.<br>    - db_path (str): Path to the Access database for listing.<br>    - table_name (str): Name of the table in database.<br>    - section (str): Section filter.<br>    - ... (similar to process_access_data)<br><br>    Returns:<br>    - dict: Paths and summaries for declarative and comparisons.<br>    &quot;&quot;&quot;<br>    logger = logging.getLogger(__name__)<br>    punctuation = re.escape(string.punctuation)<br>    output_format = &#39;xlsx&#39; if output_format.lower() == &#39;excel&#39; else output_format.lower()<br>    if output_format not in [&quot;xlsx&quot;, &quot;csv&quot;, &quot;json&quot;]:<br>        raise ValueError(f&quot;Unsupported output format: {output_format}&quot;)<br><br>    try:<br>        # Get directory structure (assume already created)<br>        created_dirs = setup_directory_structure(ministry, base_path)<br>        base_dir = created_dirs[0]<br>        reports_dir = created_dirs[-1]<br>        declaration_dir = created_dirs[2]  # DECLARATION<br><br>        # Initialize global summaries<br>        global_summaries = {}<br><br>        # Initialize summaries<br>        summaries = {&quot;donnees_rows&quot;: 0, &quot;missing_matricule_mod_rows&quot;: 0, &quot;missing_matricule_mod_unique_rows&quot;: 0}<br><br>        # Read data from Excel<br>        data = pd.read_excel(excel_path)<br>        logger.info(f&quot;Fetched {len(data)} rows from declarative Excel for section {section}&quot;)<br><br>        # Assume columns are similar; filter for section if present<br>        if &#39;Section&#39; in data.columns:<br>            data = data[data[&#39;Section&#39;].str.contains(section, case=False, na=False)]<br><br>        # Apply filters similar to listing<br>        original_row_count = len(data)<br>        filtered_out_rows = pd.DataFrame(columns=data.columns)<br>        if filter_conditions:<br>            for col, condition in filter_conditions.items():<br>                if col in data.columns:<br>                    if isinstance(condition, str):<br>                        mask = data[col].astype(str).str.contains(condition, case=False, regex=True, na=False)<br>                    else:<br>                        mask = data[col].astype(str).str.contains(&#39;|&#39;.join(condition), case=False, regex=True, na=False)<br>                    filtered_out_rows = pd.concat([filtered_out_rows, data[~mask]], ignore_index=True)<br>                    data = data[mask]<br><br>        if filter_query:<br>            filtered_out_rows = pd.concat([filtered_out_rows, data.query(f&quot;~({filter_query})&quot;, engine=&#39;python&#39;)], ignore_index=True)<br>            data = data.query(filter_query, engine=&#39;python&#39;).copy()<br><br>        # Update summaries with processed data rows<br>        summaries[&quot;donnees_rows&quot;] = len(data)<br><br>        # Data cleaning<br>        if &#39;noms&#39; in data.columns and &#39;matricule&#39; in data.columns:<br>            data.loc[:, &quot;nomscompact&quot;] = data[&quot;noms&quot;].astype(str).str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).str.upper().fillna(&quot;&quot;)<br>            data.loc[:, &quot;matricule_mod&quot;] = data[&quot;matricule&quot;].astype(str).str.upper().str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br>        else:<br>            raise ValueError(&quot;Declarative Excel must have &#39;noms&#39;, &#39;matricule&#39; columns.&quot;)<br><br>        # Validate output columns<br>        output_columns = data.columns.tolist()<br><br>        # Extract missing matricule_mod<br>        excluded_values = [&quot;&quot;, &quot;nu&quot;, &quot;Nu&quot;, &quot;uN&quot;, &quot;NU&quot;, &quot;nan&quot;, &quot;NaN&quot;, &quot;naN&quot;, &quot;Nan&quot;, &quot;NAN&quot;, &quot;nAn&quot;, &quot;Nat&quot;, &quot;naT&quot;, &quot;NaT&quot;, &quot;nAt&quot;, &quot;0&quot;, &quot;00&quot;, &quot;000&quot;, &quot;0000&quot;, &quot;00000&quot;, &quot;000000&quot;, &quot;0000000&quot;]<br>        missing_matricule_mod = data[data[&quot;matricule_mod&quot;].isin(excluded_values)]<br>        missing_path = os.path.join(reports_dir, f&quot;missing_matricule_mod_decl.{output_format}&quot;)<br>        if not missing_matricule_mod.empty:<br>            missing_matricule_mod.to_excel(missing_path, index=False, engine=&#39;openpyxl&#39;) if output_format == &quot;xlsx&quot; else missing_matricule_mod.to_csv(missing_path, index=False, encoding=&#39;utf-8&#39;) if output_format == &quot;csv&quot; else missing_matricule_mod.to_json(missing_path, orient=&#39;records&#39;, lines=True)<br>            global_summaries[&quot;missing_matricule_mod&quot;] = calculate_summary_metrics(missing_matricule_mod)<br>            # Add unique for missing<br>            unique_missing = missing_matricule_mod.drop_duplicates(subset=&quot;nomscompact&quot;, keep=&quot;first&quot;)<br>            unique_missing_path = os.path.join(reports_dir, f&quot;missing_matricule_mod_decl_unique.{output_format}&quot;)<br>            unique_missing.to_excel(unique_missing_path, index=False, engine=&#39;openpyxl&#39;) if output_format == &quot;xlsx&quot; else unique_missing.to_csv(unique_missing_path, index=False, encoding=&#39;utf-8&#39;) if output_format == &quot;csv&quot; else unique_missing.to_json(unique_missing_path, orient=&#39;records&#39;, lines=True)<br>            logger.info(f&quot;Unique missing matricule_mod (decl) saved to: {unique_missing_path}&quot;)<br>            global_summaries[&quot;missing_matricule_mod_unique&quot;] = calculate_summary_metrics(unique_missing)<br>            summaries[&quot;missing_matricule_mod_rows&quot;] = len(missing_matricule_mod)<br>            summaries[&quot;missing_matricule_mod_unique_rows&quot;] = len(unique_missing)<br>        else:<br>            summaries[&quot;missing_matricule_mod_rows&quot;] = 0<br>            summaries[&quot;missing_matricule_mod_unique_rows&quot;] = 0<br><br>        # Save initial declarative data<br>        initial_output_path = os.path.join(declaration_dir, f&quot;donnees_decl_{section}.{output_format}&quot;)<br>        data.to_excel(initial_output_path, index=False, engine=&#39;openpyxl&#39;) if output_format == &quot;xlsx&quot; else data.to_csv(initial_output_path, index=False, encoding=&#39;utf-8&#39;) if output_format == &quot;csv&quot; else data.to_json(initial_output_path, orient=&#39;records&#39;, lines=True)<br>        logger.info(f&quot;Declarative data saved to: {initial_output_path}&quot;)<br>        global_summaries[&quot;donnees&quot;] = calculate_summary_metrics(data)<br><br>        # Deduplicate<br>        results_dir = create_custom_results_directory(base_dir, {&quot;original_rows&quot;: len(data), &quot;unique_rows&quot;: len(data), &quot;duplicates_saved&quot;: 0})<br>        if deduplicate_columns:<br>            for col in deduplicate_columns:<br>                result = remove_duplicates_excel(<br>                    data=data,<br>                    column=col,<br>                    results_dir=results_dir,<br>                    output_format=output_format,<br>                    case_sensitive=case_sensitive,<br>                    generate_unique_duplicates=True,<br>                    prefix=&quot;_decl&quot;<br>                )<br>                summaries[col] = result[&quot;summary&quot;]<br>                summaries[col][&quot;file_paths&quot;] = result[&quot;file_paths&quot;]<br>                global_summaries.update(result[&quot;file_summaries&quot;])<br><br>        # Comparisons with listing<br>        comparisons = {}<br>        comparisons_paths = {}<br>        conn_str = f&quot;Driver={{Microsoft Access Driver (*.mdb, *.accdb)}};DBQ={db_path};&quot;<br>        conn = pyodbc.connect(conn_str)<br>        cursor = conn.cursor()<br><br>        # Unique from declarative<br>        unique_matricule_mod = [x for x in data[&quot;matricule_mod&quot;].unique() if x not in excluded_values]<br>        unique_nomscompact = [x for x in data[&quot;nomscompact&quot;].unique() if x not in excluded_values]<br><br>        # Query for other sections with Base &gt; 0<br>        query_other = f&quot;SELECT * FROM {table_name} WHERE Section NOT LIKE &#39;%{section}%&#39; AND Categorie &lt;&gt; &#39;BUDGETS ANNEXES&#39; AND Base &gt; 0&quot;<br>        cursor.execute(query_other)<br>        rows = cursor.fetchall()<br>        columns_db = [col[0] for col in cursor.description]<br>        other_sections_data = pd.DataFrame([tuple(row) for row in rows], columns=columns_db)<br><br>        if not other_sections_data.empty:<br>            other_sections_data.loc[:, &quot;NomPostnom&quot;] = other_sections_data[&quot;NomPostnom&quot;].astype(str).str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br>            other_sections_data.loc[:, &quot;Prenom&quot;] = other_sections_data[&quot;Prenom&quot;].astype(str).str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br>            other_sections_data.loc[:, &quot;nomscompact&quot;] = other_sections_data[&quot;NomPostnom&quot;].str.cat(other_sections_data[&quot;Prenom&quot;], sep=&quot;&quot;).str.upper()<br>            other_sections_data.loc[:, &quot;matricule_mod&quot;] = other_sections_data[&quot;Matricule&quot;].astype(str).str.upper().str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br><br>        # Declared but paid in other sections by matricule<br>        declared_paid_other_mat = other_sections_data[other_sections_data[&quot;matricule_mod&quot;].isin(unique_matricule_mod)] if not other_sections_data.empty else pd.DataFrame()<br>        if not declared_paid_other_mat.empty:<br>            path = os.path.join(results_dir, &quot;declared_paid_other_by_matricule.xlsx&quot;)<br>            declared_paid_other_mat.to_excel(path, index=False, engine=&#39;openpyxl&#39;)<br>            global_summaries[&quot;declared_paid_other_by_matricule&quot;] = calculate_summary_metrics(declared_paid_other_mat)<br>            unique_data = declared_paid_other_mat.drop_duplicates(subset=&quot;matricule_mod&quot;, keep=&quot;first&quot;)<br>            unique_path = os.path.join(results_dir, &quot;declared_paid_other_by_matricule_unique.xlsx&quot;)<br>            unique_data.to_excel(unique_path, index=False, engine=&#39;openpyxl&#39;)<br>            global_summaries[&quot;declared_paid_other_by_matricule_unique&quot;] = calculate_summary_metrics(unique_data)<br>            comparisons[&quot;declared_paid_other_by_matricule_records&quot;] = len(declared_paid_other_mat)<br>            comparisons[&quot;declared_paid_other_by_matricule&quot;] = len(unique_data)<br>            comparisons[&quot;sum_declared_paid_other_by_matricule&quot;] = global_summaries[&quot;declared_paid_other_by_matricule&quot;][&quot;sum&quot;]<br>            comparisons[&quot;sum_declared_paid_other_by_matricule_unique&quot;] = global_summaries[&quot;declared_paid_other_by_matricule_unique&quot;][&quot;sum&quot;]<br>            comparisons_paths[&quot;declared_paid_other_by_matricule&quot;] = path<br>            comparisons_paths[&quot;declared_paid_other_by_matricule_unique&quot;] = unique_path<br><br>        # By nomscompact<br>        declared_paid_other_nom = other_sections_data[other_sections_data[&quot;nomscompact&quot;].isin(unique_nomscompact)] if not other_sections_data.empty else pd.DataFrame()<br>        if not declared_paid_other_nom.empty:<br>            path = os.path.join(results_dir, &quot;declared_paid_other_by_nomscompact.xlsx&quot;)<br>            declared_paid_other_nom.to_excel(path, index=False, engine=&#39;openpyxl&#39;)<br>            global_summaries[&quot;declared_paid_other_by_nomscompact&quot;] = calculate_summary_metrics(declared_paid_other_nom)<br>            unique_data = declared_paid_other_nom.drop_duplicates(subset=&quot;nomscompact&quot;, keep=&quot;first&quot;)<br>            unique_path = os.path.join(results_dir, &quot;declared_paid_other_by_nomscompact_unique.xlsx&quot;)<br>            unique_data.to_excel(unique_path, index=False, engine=&#39;openpyxl&#39;)<br>            global_summaries[&quot;declared_paid_other_by_nomscompact_unique&quot;] = calculate_summary_metrics(unique_data)<br>            comparisons[&quot;declared_paid_other_by_nomscompact_records&quot;] = len(declared_paid_other_nom)<br>            comparisons[&quot;declared_paid_other_by_nomscompact&quot;] = len(unique_data)<br>            comparisons[&quot;sum_declared_paid_other_by_nomscompact&quot;] = global_summaries[&quot;declared_paid_other_by_nomscompact&quot;][&quot;sum&quot;]<br>            comparisons[&quot;sum_declared_paid_other_by_nomscompact_unique&quot;] = global_summaries[&quot;declared_paid_other_by_nomscompact_unique&quot;][&quot;sum&quot;]<br>            comparisons_paths[&quot;declared_paid_other_by_nomscompact&quot;] = path<br>            comparisons_paths[&quot;declared_paid_other_by_nomscompact_unique&quot;] = unique_path<br><br>        # Query for same section with Base &gt; 0<br>        query_same = f&quot;SELECT * FROM {table_name} WHERE Section LIKE &#39;%{section}%&#39; AND Categorie &lt;&gt; &#39;BUDGETS ANNEXES&#39; AND Base &gt; 0&quot;<br>        cursor.execute(query_same)<br>        rows = cursor.fetchall()<br>        same_section_data = pd.DataFrame([tuple(row) for row in rows], columns=columns_db)<br><br>        if not same_section_data.empty:<br>            same_section_data.loc[:, &quot;NomPostnom&quot;] = same_section_data[&quot;NomPostnom&quot;].astype(str).str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br>            same_section_data.loc[:, &quot;Prenom&quot;] = same_section_data[&quot;Prenom&quot;].astype(str).str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br>            same_section_data.loc[:, &quot;nomscompact&quot;] = same_section_data[&quot;NomPostnom&quot;].str.cat(same_section_data[&quot;Prenom&quot;], sep=&quot;&quot;).str.upper()<br>            same_section_data.loc[:, &quot;matricule_mod&quot;] = same_section_data[&quot;Matricule&quot;].astype(str).str.upper().str.replace(f&quot;[{punctuation}]&quot;, &quot;&quot;, regex=True).str.replace(&quot; &quot;, &quot;&quot;, regex=True).fillna(&quot;&quot;)<br><br>        # Declared and in listing by matricule<br>        declared_in_listing_mat = same_section_data[same_section_data[&quot;matricule_mod&quot;].isin(unique_matricule_mod)] if not same_section_data.empty else pd.DataFrame()<br>        if not declared_in_listing_mat.empty:<br>            path = os.path.join(results_dir, &quot;declared_in_listing_by_matricule.xlsx&quot;)<br>            declared_in_listing_mat.to_excel(path, index=False, engine=&#39;openpyxl&#39;)<br>            global_summaries[&quot;declared_in_listing_by_matricule&quot;] = calculate_summary_metrics(declared_in_listing_mat)<br>            unique_data = declared_in_listing_mat.drop_duplicates(subset=&quot;matricule_mod&quot;, keep=&quot;first&quot;)<br>            unique_path = os.path.join(results_dir, &quot;declared_in_listing_by_matricule_unique.xlsx&quot;)<br>            unique_data.to_excel(unique_path, index=False, engine=&#39;openpyxl&#39;)<br>            global_summaries[&quot;declared_in_listing_by_matricule_unique&quot;] = calculate_summary_metrics(unique_data)<br>            comparisons[&quot;declared_in_listing_by_matricule_records&quot;] = len(declared_in_listing_mat)<br>            comparisons[&quot;declared_in_listing_by_matricule&quot;] = len(unique_data)<br>            comparisons[&quot;sum_declared_in_listing_by_matricule&quot;] = global_summaries[&quot;declared_in_listing_by_matricule&quot;][&quot;sum&quot;]<br>            comparisons[&quot;sum_declared_in_listing_by_matricule_unique&quot;] = global_summaries[&quot;declared_in_listing_by_matricule_unique&quot;][&quot;sum&quot;]<br>            comparisons_paths[&quot;declared_in_listing_by_matricule&quot;] = path<br>            comparisons_paths[&quot;declared_in_listing_by_matricule_unique&quot;] = unique_path<br><br>        # By nomscompact<br>        declared_in_listing_nom = same_section_data[same_section_data[&quot;nomscompact&quot;].isin(unique_nomscompact)] if not same_section_data.empty else pd.DataFrame()<br>        if not declared_in_listing_nom.empty:<br>            path = os.path.join(results_dir, &quot;declared_in_listing_by_nomscompact.xlsx&quot;)<br>            declared_in_listing_nom.to_excel(path, index=False, engine=&#39;openpyxl&#39;)<br>            global_summaries[&quot;declared_in_listing_by_nomscompact&quot;] = calculate_summary_metrics(declared_in_listing_nom)<br>            unique_data = declared_in_listing_nom.drop_duplicates(subset=&quot;nomscompact&quot;, keep=&quot;first&quot;)<br>            unique_path = os.path.join(results_dir, &quot;declared_in_listing_by_nomscompact_unique.xlsx&quot;)<br>            unique_data.to_excel(unique_path, index=False, engine=&#39;openpyxl&#39;)<br>            global_summaries[&quot;declared_in_listing_by_nomscompact_unique&quot;] = calculate_summary_metrics(unique_data)<br>            comparisons[&quot;declared_in_listing_by_nomscompact_records&quot;] = len(declared_in_listing_nom)<br>            comparisons[&quot;declared_in_listing_by_nomscompact&quot;] = len(unique_data)<br>            comparisons[&quot;sum_declared_in_listing_by_nomscompact&quot;] = global_summaries[&quot;declared_in_listing_by_nomscompact&quot;][&quot;sum&quot;]<br>            comparisons[&quot;sum_declared_in_listing_by_nomscompact_unique&quot;] = global_summaries[&quot;declared_in_listing_by_nomscompact_unique&quot;][&quot;sum&quot;]<br>            comparisons_paths[&quot;declared_in_listing_by_nomscompact&quot;] = path<br>            comparisons_paths[&quot;declared_in_listing_by_nomscompact_unique&quot;] = unique_path<br><br>        # Non-declared but paid in section by matricule<br>        non_declared_paid_mat = same_section_data[~same_section_data[&#39;matricule_mod&#39;].isin(data[&#39;matricule_mod&#39;])]<br>        if not non_declared_paid_mat.empty:<br>            path = os.path.join(results_dir, &quot;non_declared_paid_section_by_matricule.xlsx&quot;)<br>            non_declared_paid_mat.to_excel(path, index=False, engine=&#39;openpyxl&#39;)<br>            global_summaries[&quot;non_declared_paid_section_by_matricule&quot;] = calculate_summary_metrics(non_declared_paid_mat)<br>            unique_data = non_declared_paid_mat.drop_duplicates(subset=&quot;matricule_mod&quot;, keep=&quot;first&quot;)<br>            unique_path = os.path.join(results_dir, &quot;non_declared_paid_section_by_matricule_unique.xlsx&quot;)<br>            unique_data.to_excel(unique_path, index=False, engine=&#39;openpyxl&#39;)<br>            global_summaries[&quot;non_declared_paid_section_by_matricule_unique&quot;] = calculate_summary_metrics(unique_data)<br>            comparisons[&quot;non_declared_paid_section_by_matricule_records&quot;] = len(non_declared_paid_mat)<br>            comparisons[&quot;non_declared_paid_section_by_matricule&quot;] = len(unique_data)<br>            comparisons[&quot;sum_non_declared_paid_section_by_matricule&quot;] = global_summaries[&quot;non_declared_paid_section_by_matricule&quot;][&quot;sum&quot;]<br>            comparisons[&quot;sum_non_declared_paid_section_by_matricule_unique&quot;] = global_summaries[&quot;non_declared_paid_section_by_matricule_unique&quot;][&quot;sum&quot;]<br>            comparisons_paths[&quot;non_declared_paid_section_by_matricule&quot;] = path<br>            comparisons_paths[&quot;non_declared_paid_section_by_matricule_unique&quot;] = unique_path<br><br>        # By nomscompact<br>        non_declared_paid_nom = same_section_data[~same_section_data[&#39;nomscompact&#39;].isin(data[&#39;nomscompact&#39;])]<br>        if not non_declared_paid_nom.empty:<br>            path = os.path.join(results_dir, &quot;non_declared_paid_section_by_nomscompact.xlsx&quot;)<br>            non_declared_paid_nom.to_excel(path, index=False, engine=&#39;openpyxl&#39;)<br>            global_summaries[&quot;non_declared_paid_section_by_nomscompact&quot;] = calculate_summary_metrics(non_declared_paid_nom)<br>            unique_data = non_declared_paid_nom.drop_duplicates(subset=&quot;nomscompact&quot;, keep=&quot;first&quot;)<br>            unique_path = os.path.join(results_dir, &quot;non_declared_paid_section_by_nomscompact_unique.xlsx&quot;)<br>            unique_data.to_excel(unique_path, index=False, engine=&#39;openpyxl&#39;)<br>            global_summaries[&quot;non_declared_paid_section_by_nomscompact_unique&quot;] = calculate_summary_metrics(unique_data)<br>            comparisons[&quot;non_declared_paid_section_by_nomscompact_records&quot;] = len(non_declared_paid_nom)<br>            comparisons[&quot;non_declared_paid_section_by_nomscompact&quot;] = len(unique_data)<br>            comparisons[&quot;sum_non_declared_paid_section_by_nomscompact&quot;] = global_summaries[&quot;non_declared_paid_section_by_nomscompact&quot;][&quot;sum&quot;]<br>            comparisons[&quot;sum_non_declared_paid_section_by_nomscompact_unique&quot;] = global_summaries[&quot;non_declared_paid_section_by_nomscompact_unique&quot;][&quot;sum&quot;]<br>            comparisons_paths[&quot;non_declared_paid_section_by_nomscompact&quot;] = path<br>            comparisons_paths[&quot;non_declared_paid_section_by_nomscompact_unique&quot;] = unique_path<br><br>        cursor.close()<br>        conn.close()<br><br>        # Save global summary for declarative<br>        global_summary_path = os.path.join(reports_dir, f&quot;global_summary_decl.{output_format}&quot;)<br>        save_global_summary(global_summaries, global_summary_path, output_format)<br><br>        return {<br>            &quot;initial_output_path&quot;: initial_output_path,<br>            &quot;summaries&quot;: summaries,<br>            &quot;global_summary_path&quot;: global_summary_path,<br>            &quot;comparisons&quot;: comparisons,<br>            &quot;comparisons_paths&quot;: comparisons_paths,<br>            &quot;missing_matricule_mod_path&quot;: missing_path if not missing_matricule_mod.empty else None,<br>            &quot;missing_matricule_mod_unique_path&quot;: unique_missing_path if &#39;unique_missing_path&#39; in locals() else None,<br>            &quot;data&quot;: data,<br>            &quot;global_summaries&quot;: global_summaries<br>        }<br><br>    except Exception as e:<br>        logger.error(f&quot;Error processing declarative data: {e}&quot;)<br>        raise<br><br># Example usage<br>if __name__ == &quot;__main__&quot;:<br>    MINISTRY = &quot;ESSAIE&quot;<br>    DB_PATH = &quot;FICHIERDEPART/Database1.accdb&quot;<br>    TABLE_NAME = &quot;Tab_AutresRegimes_T1_2024&quot;<br>    SECTION = &quot;tourisme&quot;<br>    CATEGORIE = None<br>    UNITE_AFFECTATION = None<br>    OUTPUT_COLUMNS = [<br>        &quot;CodeAdm&quot;, &quot;Categorie&quot;, &quot;IdPersonnel&quot;, &quot;Matricule&quot;, &quot;NomPostnom&quot;, &quot;Prenom&quot;,<br>        &quot;Genre&quot;, &quot;DateNaissance&quot;, &quot;CodeGrade&quot;, &quot;Grade&quot;, &quot;CodeUniteAffectation&quot;,<br>        &quot;UniteAffectation&quot;, &quot;CodeEntiteRem&quot;, &quot;EntiteRemuneree&quot;, &quot;CodeBanque&quot;,<br>        &quot;Banque&quot;, &quot;CodeProvince&quot;, &quot;Province&quot;, &quot;CodeSection&quot;, &quot;Section&quot;, &quot;Base&quot;,<br>        &quot;Transport&quot;, &quot;Prime&quot;, &quot;Logement&quot;, &quot;Pension_Rente&quot;, &quot;IPR&quot;, &quot;Retenue&quot;,<br>        &quot;CNSS&quot;, &quot;CNSSAP&quot;, &quot;MontantNet&quot;<br>    ]<br>    FILTER_QUERY = &quot;Base &gt; 0&quot;<br>    FILTER_CONDITIONS = {}<br>    DEDUPLICATE_COLUMNS = [&quot;matricule_mod&quot;, &quot;nomscompact&quot;]<br>    PROJECTION_COLUMNS = [&quot;Matricule&quot;, &quot;NomPostnom&quot;, &quot;Prenom&quot;, &quot;nomscompact&quot;, &quot;matricule_mod&quot;]<br>    DECLARATIVE_EXCEL_PATH = &quot;FICHIERDEPART/declarative.xlsx&quot;  # Assume this is the path to the declarative Excel file<br><br>    # Process listing<br>    result_listing = process_access_data(<br>        db_path=DB_PATH,<br>        table_name=TABLE_NAME,<br>        section=SECTION,<br>        categorie=CATEGORIE,<br>        unite_affectation=UNITE_AFFECTATION,<br>        output_columns=OUTPUT_COLUMNS,<br>        output_format=&quot;xlsx&quot;,<br>        ministry=MINISTRY,<br>        filter_query=FILTER_QUERY,<br>        filter_conditions=FILTER_CONDITIONS,<br>        deduplicate_columns=DEDUPLICATE_COLUMNS,<br>        case_sensitive=False,<br>        projection_columns=PROJECTION_COLUMNS<br>    )<br>    print(&quot;Listing Processing Result:&quot;, result_listing)<br><br>    # Process declarative<br>    result_decl = process_excel_declarative(<br>        excel_path=DECLARATIVE_EXCEL_PATH,<br>        db_path=DB_PATH,<br>        table_name=TABLE_NAME,<br>        section=SECTION,<br>        output_columns=None,<br>        output_format=&quot;xlsx&quot;,<br>        ministry=MINISTRY,<br>        filter_query=None,  # No Base in declarative, adjust if needed<br>        filter_conditions=FILTER_CONDITIONS,<br>        deduplicate_columns=DEDUPLICATE_COLUMNS,<br>        case_sensitive=False,<br>        projection_columns=None<br>    )<br>    print(&quot;Declarative Processing Result:&quot;, result_decl)<br><br>    # Collect annex paths<br>    annex_paths = {}<br>    annex_paths[f&quot;donnees_{SECTION}.xlsx&quot;] = result_listing[&quot;initial_output_path&quot;]<br>    annex_paths[f&quot;donnees_decl_{SECTION}.xlsx&quot;] = result_decl[&quot;initial_output_path&quot;]<br>    annex_paths[&quot;missing_matricule_mod.xlsx&quot;] = result_listing[&quot;missing_matricule_mod_path&quot;]<br>    annex_paths[&quot;missing_matricule_mod_unique.xlsx&quot;] = result_listing[&quot;missing_matricule_mod_unique_path&quot;]<br>    annex_paths[&quot;missing_matricule_mod_decl.xlsx&quot;] = result_decl[&quot;missing_matricule_mod_path&quot;]<br>    annex_paths[&quot;missing_matricule_mod_decl_unique.xlsx&quot;] = result_decl[&quot;missing_matricule_mod_unique_path&quot;]<br>    if &quot;matricule_mod&quot; in result_listing[&quot;summaries&quot;]:<br>        annex_paths[&quot;duplicates_by_matricule_mod.xlsx&quot;] = result_listing[&quot;summaries&quot;][&quot;matricule_mod&quot;][&quot;file_paths&quot;][&quot;duplicates&quot;]<br>        annex_paths[&quot;duplicates_by_matricule_mod_unique.xlsx&quot;] = result_listing[&quot;summaries&quot;][&quot;matricule_mod&quot;][&quot;file_paths&quot;][&quot;unique_duplicates&quot;]<br>    if &quot;nomscompact&quot; in result_listing[&quot;summaries&quot;]:<br>        annex_paths[&quot;duplicates_by_nomscompact.xlsx&quot;] = result_listing[&quot;summaries&quot;][&quot;nomscompact&quot;][&quot;file_paths&quot;][&quot;duplicates&quot;]<br>        annex_paths[&quot;duplicates_by_nomscompact_unique.xlsx&quot;] = result_listing[&quot;summaries&quot;][&quot;nomscompact&quot;][&quot;file_paths&quot;][&quot;unique_duplicates&quot;]<br>    if &quot;matricule_mod&quot; in result_decl[&quot;summaries&quot;]:<br>        annex_paths[&quot;duplicates_by_matricule_mod_decl.xlsx&quot;] = result_decl[&quot;summaries&quot;][&quot;matricule_mod&quot;][&quot;file_paths&quot;][&quot;duplicates&quot;]<br>        annex_paths[&quot;duplicates_by_matricule_mod_decl_unique.xlsx&quot;] = result_decl[&quot;summaries&quot;][&quot;matricule_mod&quot;][&quot;file_paths&quot;][&quot;unique_duplicates&quot;]<br>    if &quot;nomscompact&quot; in result_decl[&quot;summaries&quot;]:<br>        annex_paths[&quot;duplicates_by_nomscompact_decl.xlsx&quot;] = result_decl[&quot;summaries&quot;][&quot;nomscompact&quot;][&quot;file_paths&quot;][&quot;duplicates&quot;]<br>        annex_paths[&quot;duplicates_by_nomscompact_decl_unique.xlsx&quot;] = result_decl[&quot;summaries&quot;][&quot;nomscompact&quot;][&quot;file_paths&quot;][&quot;unique_duplicates&quot;]<br>    annex_paths[&quot;agents_in_other_sections_by_matricule_mod.xlsx&quot;] = result_listing[&quot;agents_in_other_sections_by_matricule_mod_filtered_path&quot;]<br>    annex_paths[&quot;agents_in_other_sections_by_nomscompact.xlsx&quot;] = result_listing[&quot;agents_in_other_sections_by_nomscompact_filtered_path&quot;]<br>    annex_paths[&quot;agents_in_other_sections_by_matricule_mod_unique.xlsx&quot;] = result_listing[&quot;agents_in_other_sections_by_matricule_mod_filtered_unique_path&quot;]<br>    annex_paths[&quot;agents_in_other_sections_by_nomscompact_unique.xlsx&quot;] = result_listing[&quot;agents_in_other_sections_by_nomscompact_filtered_unique_path&quot;]<br>    annex_paths.update(result_decl[&quot;comparisons_paths&quot;])<br>    annex_paths[&quot;declared_paid_other_by_matricule_unique.xlsx&quot;] = os.path.join(os.path.dirname(result_decl[&quot;comparisons_paths&quot;].get(&quot;declared_paid_other_by_matricule&quot;, &quot;&quot;)), &quot;declared_paid_other_by_matricule_unique.xlsx&quot;) if &quot;declared_paid_other_by_matricule&quot; in result_decl[&quot;comparisons_paths&quot;] else None<br>    annex_paths[&quot;declared_paid_other_by_nomscompact_unique.xlsx&quot;] = os.path.join(os.path.dirname(result_decl[&quot;comparisons_paths&quot;].get(&quot;declared_paid_other_by_nomscompact&quot;, &quot;&quot;)), &quot;declared_paid_other_by_nomscompact_unique.xlsx&quot;) if &quot;declared_paid_other_by_nomscompact&quot; in result_decl[&quot;comparisons_paths&quot;] else None<br>    annex_paths[&quot;declared_in_listing_by_matricule_unique.xlsx&quot;] = os.path.join(os.path.dirname(result_decl[&quot;comparisons_paths&quot;].get(&quot;declared_in_listing_by_matricule&quot;, &quot;&quot;)), &quot;declared_in_listing_by_matricule_unique.xlsx&quot;) if &quot;declared_in_listing_by_matricule&quot; in result_decl[&quot;comparisons_paths&quot;] else None<br>    annex_paths[&quot;declared_in_listing_by_nomscompact_unique.xlsx&quot;] = os.path.join(os.path.dirname(result_decl[&quot;comparisons_paths&quot;].get(&quot;declared_in_listing_by_nomscompact&quot;, &quot;&quot;)), &quot;declared_in_listing_by_nomscompact_unique.xlsx&quot;) if &quot;declared_in_listing_by_nomscompact&quot; in result_decl[&quot;comparisons_paths&quot;] else None<br>    annex_paths[&quot;non_declared_paid_section_by_matricule_unique.xlsx&quot;] = os.path.join(os.path.dirname(result_decl[&quot;comparisons_paths&quot;].get(&quot;non_declared_paid_section_by_matricule&quot;, &quot;&quot;)), &quot;non_declared_paid_section_by_matricule_unique.xlsx&quot;) if &quot;non_declared_paid_section_by_matricule&quot; in result_decl[&quot;comparisons_paths&quot;] else None<br>    annex_paths[&quot;non_declared_paid_section_by_nomscompact_unique.xlsx&quot;] = os.path.join(os.path.dirname(result_decl[&quot;comparisons_paths&quot;].get(&quot;non_declared_paid_section_by_nomscompact&quot;, &quot;&quot;)), &quot;non_declared_paid_section_by_nomscompact_unique.xlsx&quot;) if &quot;non_declared_paid_section_by_nomscompact&quot; in result_decl[&quot;comparisons_paths&quot;] else None<br><br>    # Generate combined report<br>    report_path = os.path.join(os.path.dirname(result_listing[&quot;global_summary_path&quot;]), &quot;rapport.xlsx&quot;)<br>    generate_excel_report(<br>        summaries_listing=result_listing[&quot;summaries&quot;],<br>        global_summaries_listing=result_listing[&quot;global_summaries&quot;],<br>        summaries_decl=result_decl[&quot;summaries&quot;],<br>        global_summaries_decl=result_decl[&quot;global_summaries&quot;],<br>        comparisons=result_decl[&quot;comparisons&quot;],<br>        report_path=report_path,<br>        section=SECTION,<br>        trimestre=&quot;T1&quot;,<br>        annee=2025,<br>        annex_paths=annex_paths,<br>        output_format=&quot;xlsx&quot;<br>    )</pre><h3>Performance and Scalability</h3><p>Tested with 7,584 rows, the script handles cleaning, deduplication, and report generation in seconds to minutes, depending on data size. For larger datasets, Pandas’ efficiency ensures scalability, though database queries may be bottlenecks — optimize with indexes if needed.</p><p>Potential improvements:</p><ul><li>Parallel processing for large files using Dask.</li><li>Integration with cloud databases (e.g., SQL Server).</li><li>UI for non-coders using Streamlit or Flask.</li></ul><h3>Conclusion</h3><p>This payroll processing system is a testament to Python’s power in automating complex data tasks. By handling deduplication, summaries, and reporting in one script, it reduces errors and saves time. If you’re facing similar challenges, adapt this code — it’s open for extension. Feel free to comment or reach out for collaborations!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66dec6c57b46" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>