analitics

Pages

Sunday, October 4, 2026

tkinter : PyTorch and Keras on pydroid3.

Today, simple python script with pytorch and keras on android pydroid application.
This script is a Tkinter graphical application designed to test and verify PyTorch and Keras packages in Pydroid 3. Right at launch, it tracks execution time down to milliseconds and displays the installed package versions in a status panel. All diagnostics run on a background thread to keep the user interface responsive. For PyTorch, the script tests matrix inversion, automatic gradient calculations using Autograd, data processing through a neural network linear layer, and eigenvalue decomposition. For Keras, the script verifies building a Sequential model with dense layers, compiling and training it on synthetic data for 3 epochs, and running a final prediction to confirm end-to-end execution.
This is the result of the running python script:
Let's see the source code:
import os
import time
import threading
import tkinter as tk
from tkinter import ttk, scrolledtext

# Set Keras backend to torch
os.environ["KERAS_BACKEND"] = "torch"

class AppCheck(tk.Tk):
    def __init__(self):
        self.start_time = time.time()
        
        super().__init__()
        self.title("PyTorch & Keras Inspector")
        self.geometry("480x600")
        
        self.style = ttk.Style(self)
        self.style.theme_use('clam')
        
        self.create_widgets()
        
        # Log UI startup time
        ui_ready = self.get_elapsed_str()
        self.log(f"{ui_ready} Tkinter UI initialized")
        
        # Initial package check
        self.check_initial_imports()

    def get_elapsed_str(self):
        """Returns elapsed time in MM:SS.mmm format without brackets."""
        elapsed = time.time() - self.start_time
        minutes = int(elapsed // 60)
        seconds = int(elapsed % 60)
        millis = int((elapsed - int(elapsed)) * 1000)
        return f"+{minutes:02d}:{seconds:02d}.{millis:03d}"

    def create_widgets(self):
        # Status Frame
        self.info_frame = ttk.LabelFrame(self, text=" Package Status ")
        self.info_frame.pack(fill="x", padx=8, pady=4)

        self.lbl_torch = ttk.Label(self.info_frame, text="PyTorch: Checking...", font=("Helvetica", 9))
        self.lbl_torch.pack(anchor="w", padx=8, pady=2)

        self.lbl_keras = ttk.Label(self.info_frame, text="Keras: Checking...", font=("Helvetica", 9))
        self.lbl_keras.pack(anchor="w", padx=8, pady=2)

        # Run Tests Button
        self.btn_run = ttk.Button(self, text="Run Full Test Suite", command=self.start_tests_thread)
        self.btn_run.pack(pady=6)

        # Console Log Header
        ttk.Label(self, text="Execution Log:", font=("Helvetica", 9, "bold")).pack(anchor="w", padx=8)
        
        # Font size reduced to 7 to fit ~10% more content line-by-line
        self.txt_log = scrolledtext.ScrolledText(self, height=25, font=("Courier", 7))
        self.txt_log.pack(fill="both", expand=True, padx=8, pady=4)

    def log(self, message):
        """Helper to append text to the log window."""
        self.txt_log.insert(tk.END, message + "\n")
        self.txt_log.see(tk.END)

    def check_initial_imports(self):
        t_str = self.get_elapsed_str()
        self.log(f"{t_str} Checking imports...")
        
        # Check PyTorch
        try:
            import torch
            self.lbl_torch.config(text=f"PyTorch: v{torch.__version__}", foreground="green")
            self.log(f"{self.get_elapsed_str()} PyTorch v{torch.__version__} loaded successfully")
        except ImportError as e:
            self.lbl_torch.config(text="PyTorch: Not installed", foreground="red")
            self.log(f"{self.get_elapsed_str()} PyTorch import error: {e}")

        # Check Keras
        try:
            import keras
            self.lbl_keras.config(text=f"Keras: v{keras.__version__}", foreground="green")
            self.log(f"{self.get_elapsed_str()} Keras v{keras.__version__} loaded successfully")
        except ImportError as e:
            self.lbl_keras.config(text="Keras: Not installed", foreground="red")
            self.log(f"{self.get_elapsed_str()} Keras import error: {e}")

    def start_tests_thread(self):
        self.btn_run.config(state="disabled")
        threading.Thread(target=self.run_tests, daemon=True).start()

    def run_tests(self):
        self.log(f"\n{self.get_elapsed_str()} STARTING FULL TEST SUITE")

        # PYTORCH TESTS
        try:
            import torch
            
            # Test 1: Matrix Inverse
            self.log(f"{self.get_elapsed_str()} PyTorch Test 1/4 Matrix Operations")
            A = torch.tensor([[2.0, 1.0], [1.0, 4.0]])
            A_inv = torch.inverse(A)
            self.log(f"   Inverted matrix output:")
            for row in A_inv.numpy():
                self.log(f"   {row}")

            # Test 2: Autograd
            self.log(f"{self.get_elapsed_str()} PyTorch Test 2/4 Autograd Gradient Calculation")
            x = torch.tensor([3.0], requires_grad=True)
            y = x**3 + 2*x
            y.backward()
            self.log(f"   dy/dx at x=3 (expected 29.0): {x.grad.item()}")

            # Test 3: Linear Layer
            self.log(f"{self.get_elapsed_str()} PyTorch Test 3/4 Neural Network Linear Layer")
            lin = torch.nn.Linear(3, 1)
            inp = torch.randn(2, 3)
            out = lin(inp)
            self.log(f"   Output tensor shape: {out.shape}")

            # Test 4: Eigenvalues
            self.log(f"{self.get_elapsed_str()} PyTorch Test 4/4 Eigenvalue Decomposition")
            e_vals = torch.linalg.eigvals(A)
            self.log(f"   Eigenvalues: {e_vals.numpy()}")

        except Exception as e:
            self.log(f"{self.get_elapsed_str()} PyTorch Test Failed: {str(e)}")
            
        # KERAS TESTS
        try:
            import keras
            import numpy as np
            
            # Test 1: Sequential Model Creation
            self.log(f"{self.get_elapsed_str()} Keras Test 1/3 Building Sequential Model")
            model = keras.Sequential([
                keras.layers.Input(shape=(4,)),
                keras.layers.Dense(8, activation="relu"),
                keras.layers.Dense(1, activation="sigmoid")
            ])
            self.log(f"   Model created successfully with {model.count_params()} parameters")

            # Test 2: Model Compilation & Training
            self.log(f"{self.get_elapsed_str()} Keras Test 2/3 Model Compilation and Training")
            model.compile(optimizer="adam", loss="binary_crossentropy")
            
            X_train = np.random.random((32, 4))
            y_train = np.random.randint(2, size=(32, 1))
            
            history = model.fit(X_train, y_train, epochs=3, batch_size=16, verbose=0)
            final_loss = history.history['loss'][-1]
            self.log(f"   3 epochs training completed. Final loss: {final_loss:.4f}")

            # Test 3: Inference / Prediction
            self.log(f"{self.get_elapsed_str()} Keras Test 3/3 Model Prediction")
            X_test = np.random.random((2, 4))
            preds = model.predict(X_test, verbose=0)
            self.log(f"   Prediction results shape: {preds.shape}")
            for pred in preds:
                self.log(f"   Output probabilities: {pred}")

        except Exception as e:
            self.log(f"{self.get_elapsed_str()} Keras Test Failed: {str(e)}")

        self.log(f"\n{self.get_elapsed_str()} TEST SUITE COMPLETED SUCCESSFULLY")
        self.btn_run.config(state="normal")

if __name__ == "__main__":
    app = AppCheck()
    app.mainloop()

Friday, October 2, 2026

Python 3.13.16 : React frontend and python on Reflex Cloud.

Today, this simple test with artificial intelligence from reflex chat bot show how good and fast can be with one simple task.
Reflex compiles to a React frontend and a Starlette backend—the ASGI server that powers FastAPI. A familiar web stack, accessible to every Python developer. pandas, SQLAlchemy, scikit-learn, ...
After I ask to create a simple G.U.I. interface with all features from reflex, the chat bot result is this:
I built a one-page interactive playground that shows how a React-powered interface responds to Python state. Visitors can try five demos: a counter with event history, live preview controls, form validation, a searchable collection, and a dialog and toast.
Size: about 1,150 lines of Python across the page, four component modules, and four state modules. The integration section describes possibilities; it does not claim that external services are connected.
The interaction tests passed, and the page renders in the browser. I don’t have a reliable elapsed-time measurement for the build, so I can’t give an accurate creation time.
... the time of build was 4 minutes ...
Reflex comes with free features:
  • Publish 1 app on Reflex Cloud
  • Limited free usage for AI generation and hosting
  • Refills periodically
  • Public apps and public GitHub repos
  • App code download and file editing
  • Public sign-in with Reflex Auth
  • Managed database
See the result online : this webpage.

Tuesday, September 29, 2026

Python 3.13.13 : using webz.io with python.

The webz.io can be used with python:
import requests

response = requests.get(
    "https://api.webz.io/api/news?token=YOUR-TOKEN&q=%28category%3A%22economy%2C+business+and+finance%22+OR+category
    %3A%22war%2C+conflict+and+unrest%22+OR+category%3A%22science+and+technology%22+OR+category%3A%22disaster+and+accident%22
    +OR+category%3A%22environment%22+
    OR+category%3A%22labor%22%29&sort=crawled&ts=1790410006113&format=json&size=10&
    webz_reporter=true&includeSyndicated=false&allowNewsHistory=false",
    headers={"Accept": "application/json"},
)
print(response.json())

Monday, September 28, 2026

tkinter : testing RapidFuzz.

RapidFuzz is a fast and powerful Python library used for fuzzy string matching and similarity scoring. It is designed as a drop-in, high-performance alternative to the popular fuzzywuzzy library, offering significantly faster execution speeds because its core algorithms are implemented in C++ (via pybind11).
​What Can RapidFuzz Do?
​Calculate String Similarity:
It measures how similar two strings are using various mathematical distances (such as Levenshtein distance, Hamming distance, Jaro-Winkler, and Normalized Similarity metrics), returning a score typically ranging from 0 (completely different) to 100 (exact match).
​Smart Search & Extraction (process module):
You can query a list of items (such as filenames, database records, or user inputs) and instantly extract the best matches, even if the user query contains typos, misspellings, or partial words.
​Data Cleaning & Deduplication:
It helps clean messy datasets by grouping entries that represent the same entity despite slight spelling variations (e.g., matching "John Smith" with "Jon Smith").
​Lightweight & Efficient:
Unlike heavy deep learning frameworks, RapidFuzz has minimal dependencies and runs smoothly across different environments—making it ideal for desktop applications, servers, and mobile development environments like Pydroid 3.

Sunday, September 27, 2026

tkinter : fast image tool on pydroid3.

Today, one simple example fast tool for images:
Let's see this start source code:
# -*- coding: utf-8 -*-
"""Image Editor - consistent GUI sizes (Pydroid / Android)"""
import os
import shutil
import zipfile
from datetime import datetime
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, font as tkfont
from PIL import Image, ImageTk, ImageOps, ImageEnhance
VALID_EXTS = (".png", ".jpg", ".jpeg", ".bmp", ".webp", ".gif", ".tiff", ".tif")
def get_android_start_dir():
    candidates = [
        "/storage/emulated/0", "/sdcard",
        "/storage/emulated/0/Download", "/sdcard/Download",
        "/storage/emulated/0/DCIM", "/sdcard/DCIM",
        "/storage/emulated/0/Pictures", "/sdcard/Pictures",
        os.path.expanduser("\~"), "/",
    ]
    for path in candidates:
        if os.path.isdir(path) and os.access(path, os.R_OK):
            return path
    return os.getcwd()
...

Saturday, September 26, 2026

tkinter : basic portfolio for market with simulations ...

Today, one simple script tool for market. this allow to set one portofolio and use with simulations.
Let'see some screenshots:
The basic intro source code ...
import datetime
import json
import threading
import urllib.request
import tkinter as tk
from tkinter import ttk, messagebox

import matplotlib
matplotlib.use("TkAgg")
from matplotlib.figure import Figure
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg


def fetch_yahoo_history(symbol, period_years=1):
    """Descarcă istoricul zilnic de pe Yahoo Finance."""
    end_date = int(datetime.datetime.now().timestamp())
    start_date = int((datetime.datetime.now() - datetime.timedelta(days=365 * period_years)).timestamp())
    
    url = f"https://query1.finance.yahoo.com/v8/finance/chart/{symbol}?period1={start_date}&period2={end_date}&interval=1d"
    req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
    
    try:
        with urllib.request.urlopen(req, timeout=10) as resp:
            data = json.loads(resp.read().decode("utf-8"))
            result = data["chart"]["result"][0]
            timestamps = result["timestamp"]
            closes = result["indicators"]["quote"][0]["close"]
            
            history = []
            for ts, cl in zip(timestamps, closes):
                if cl is not None:
                    dt = datetime.datetime.fromtimestamp(ts)
                    history.append((dt, float(cl)))
            return history
    except Exception as e:
        print(f"Eroare la descărcare {symbol}: {e}")
        return []
        ...

Thursday, September 24, 2026

News : OpenAI python library released.

The OpenAI Python library provides convenient access to the OpenAI REST API from any Python 3.10+ application. The library includes type definitions for all request params and response fields, and offers both synchronous and asynchronous clients powered by HTTPX2.

Tuesday, September 22, 2026

News : PyPy new 8.0.0 version.

The PyPy team is proud to release version 8.0.0 of PyPy after the previous release on May 26, 2026. This is a major new version, hence the bump to 8.0.0. It is our first release of Python 3.12, which may still have some bugs so we are calling it "beta" quality.
PyPy is written in RPython, and has code generation to translate RPython into C as part of the VM build process. We have made some improvements to code generation in attempts to speed up the base interpreter.

Monday, September 21, 2026

tkinter : simple marshmallow demo.

About the marshmallow package
  • It checks if your data has the correct fields.
  • It verifies that each field has the right type.
  • It helps you validate JSON before using it.
  • It can convert Python data into clean JSON.
About your this source code:
  • It loads the marshmallow package when the app starts.
  • It reads the JSON you type in the input box.
  • It tries to convert that text into Python data.
  • It validates the data using your marshmallow schema.
  • It shows the result or the error directly in the output box.
  • It does not use print or message boxes.
Why this tool is useful
  • You can test JSON visually.
  • You can see validation errors instantly.
  • You avoid console output.
  • You keep everything inside the GUI.
Let's see the sourve code:
import json
import tkinter as tk
from tkinter import ttk

# ------------------ Package Load Test ------------------

try:
    from marshmallow import Schema, fields, ValidationError
    package_status = "Package marshmallow loaded successfully."
except Exception as e:
    package_status = "PACKAGE LOAD ERROR: " + str(e)


# ------------------ Marshmallow Schema ------------------

class PersonSchema(Schema):
    full_name = fields.Str(required=True)
    city = fields.Str(required=True)
    birth_date = fields.Date(required=True)
    nicknames = fields.List(fields.Str(), required=True)


schema = PersonSchema()


# ------------------ Tkinter UI ------------------

def process_json():
    raw = editor.get("1.0", tk.END).strip()

    output.delete("1.0", tk.END)

    # Step 1: package status
    output.insert(tk.END, package_status + "\n\n")

    # Step 2: show raw JSON
    output.insert(tk.END, "RAW JSON RECEIVED:\n" + raw + "\n\n")

    # Step 3: JSON parsing
    try:
        data = json.loads(raw)
        output.insert(tk.END, "JSON PARSED OK.\n\n")
    except Exception as e:
        output.insert(tk.END, "JSON ERROR:\n" + str(e))
        return

    # Step 4: Marshmallow validation
    try:
        result = schema.dump(data)
        output.insert(tk.END, "SCHEMA VALIDATION OK.\n\n")
    except ValidationError as e:
        output.insert(tk.END, "SCHEMA ERROR:\n" + json.dumps(e.messages, indent=2))
        return

    # Step 5: Final result
    output.insert(tk.END, "FINAL RESULT:\n" + json.dumps(result, indent=2))


root = tk.Tk()
root.title("Marshmallow Diagnostic Full Output")
root.geometry("750x550")

frm = ttk.Frame(root, padding=10)
frm.pack(fill="both", expand=True)

ttk.Label(frm, text="JSON Input:").pack(anchor="w")

editor = tk.Text(frm, height=14, width=90)
editor.pack(fill="x")

editor.insert(
    tk.END,
    json.dumps(
        {
            "full_name": "Catalin George Festila",
            "city": "Falticeni",
            "birth_date": "1976-03-07",
            "nicknames": ["catafest", "mythcat"]
        },
        indent=2
    )
)

ttk.Button(frm, text="Run", command=process_json).pack(pady=10)

ttk.Label(frm, text="Output:").pack(anchor="w")

output = tk.Text(frm, height=14, width=90)
output.pack(fill="both", expand=True)

root.mainloop()

Saturday, September 12, 2026

News : Real-Time Stock & ETF Analyzer in using tvscreener and Tkinter and pydroid3.

The tvscreener is a lightweight Python library designed to extract and analyze real-time financial data directly from TradingView's API without requiring paid API keys or complex authentication. It provides quick access to technical indicators, fundamental metrics, historical performance, and volume data for international stocks and ETFs. Explore the source code and documentation on the official tvscreener GitHub repository. The script provides a desktop interface (Tkinter GUI) powered by tvscreener logic to query market data on demand. This allow to choose a ticker symbol from the dropdown list (such as GOOGL, NVDA, AAPL, or ETFs like VUAA). Clicking Check triggers a background HTTP request without freezing the user interface, while displaying real-time progress via the progress bar. The script formats the API response into four core metric categories: Performance, Technical Indicators, Fundamentals, and Volume and Liquidity. Clicking Copy transfers the complete output directly to your system clipboard for quick sharing or note-taking.

Tuesday, September 1, 2026

News : Inkscape MCP coding agent python module.

With Inkscape MCP, your coding agent can do everything a designer does in Inkscape — sketch and reshape paths, apply effects and filters, render LaTeX equations, generate barcodes and QR codes, convert between formats, query and rewrite document structure — through plain conversation instead of menu clicks.