sabato 8 febbraio 2025

[EN] DMVCFramework Gotcha #2: Active Record

Active Record is an architectural design pattern introduced by Martin Fowler in his 2003 publication.

The Active Record pattern is built on the concept of abstracting a database table into a class that adheres to OOP principles. In this pattern, each class instance represents a single table row, while the class itself provides methods implementing all CRUD operations. Such a class encapsulates all database interaction logic, offering an object-oriented interface for data manipulation. It's worth noting that this pattern inherently creates coupling between the class structure and the underlying database table.

Key Features:

1. Database Encapsulation: All database connection details and SQL queries are encapsulated within the class

2. Data Validation: The class implements validation rules before executing database operations

3. Object Properties: Direct mapping to table columns

4. Object Relationships: Handled through methods that implement database relationships (one-to-many, many-to-many, etc.)

While Delphi itself doesn't implement Active Record natively, DMVCFramework (https://github.com/danieleteti/delphimvcframework) provides a robust implementation of this pattern.

I recently found Active Record particularly useful when developing a small application to process and store JSON data in a database. Specifically, I needed to handle JSON files generated by Anthropic from Claude.AI conversation exports.

After analyzing the JSON structure, I designed the necessary database tables. To illustrate Active Record's features, I'll focus on a specific part of the implementation.

I started by creating the Chat 'header' table, then defined its corresponding Entity in Delphi:

The entity serves as an abstraction of our database table. Let's examine its structure:

We define a class inheriting from TMVCActiveRecord:

TChats = class(TMVCActiveRecord)

TMVCActiveRecord is the framework's base class that provides all necessary data interaction methods. The entity definition's key feature lies in its field declarations, each decorated with Custom Attributes that define their behavior:

[MVCTable('chats')]: This Custom Attribute specifies which database table the class abstracts

[MVCTableField('chat_uuid', [foPrimaryKey])]: This Custom Attribute binds class fields to physical database table attributes

We create similar entities for each database table we need to interact with.

The implementation then involves reading the JSON (using the JsonDataObjects library, also available in DMVCFramework), iterating through it, and persisting the data to the database.

This code creates a new database record, but what we've covered is just a basic introduction to Active Record in DMVCFramework. There are many more features available. For instance, how do we check if a chat has already been processed?

While this example uses RQL (Resources Query Language), we could alternatively use Active Record's built-in methods, such as querying by primary key.

This practical implementation demonstrates how Active Record significantly simplifies data persistence, allowing developers to focus on business logic rather than database access details. The combination of DMVCFramework and Active Record has made JSON data import and management remarkably straightforward and efficient.

Though this example is relatively simple, Active Record in DMVCFramework supports more complex scenarios, including entity relationships, custom validations, and advanced querying capabilities.

For further exploration, I recommend reviewing the DMVCFramework documentation, which provides comprehensive examples and advanced use cases. Understanding and properly implementing this pattern can substantially improve productivity when developing Delphi applications requiring database interaction.

#codinglikeacoder

DMVCFramework Gotcha #2: Active Record

Active Record è un design pattern architetturale introdotto da Martin Fowler e descritto qui: Martin Fowler - 2003 .

Alla base del pattern Active Record vi è l'idea di astrarre una tabella del database rappresentandola con una classe; la classe seguirà i principi che caratterizzano il paradigma OOP. In questo pattern, ogni istanza della classe rappresenta una singola riga della tabella, mentre la classe stessa è specializzata con metodi che implementano tutte le operazioni CRUD. Una classe così strutturata incapsula tutta la logica necessaria per le operazioni di interazione con il database, creando un'interfaccia orientata agli oggetti per la manipolazione dei dati. È importante notare che questo pattern, per sua natura, crea un accoppiamento tra la struttura della classe e quella della tabella del database sottostante.

Alcune caratteristiche:

  1. Incapsulamento del database: Tutti i dettagli di connessione e query SQL sono nascosti all'interno della classe
  2. Validazione dei dati: La classe può implementare regole di validazione prima di eseguire operazioni sul database
  3. Proprietà dell'oggetto: Corrispondono direttamente alle colonne della tabella
  4. Relazioni tra oggetti: Possono essere gestite attraverso metodi che implementano le relazioni del database (one-to-many, many-to-many, etc.)

Delphi ad oggi non implementa Active Record.
DMVCFramework, invece,  ( https://github.com/danieleteti/delphimvcframework ) porta con se l'implementazione di Active Record.

Active Record mi è stato molto utile qualche giorno fa: avevo l'esigenza di scrivere un piccolo applicativo che prendesse in input un JSON, lo parserizzasse e memorizzasse le informazioni in esso contenute, in un Database. Il JSON in questione è il JSON generato da Anthropic dopo aver richiesto il download delle conversazioni fatte con Claude.AI.

Dopo aver analizzato la struttura del JSON, ho creato le tabelle.
Qui non vi mostro tutto il processo ma una parte di esso che mi permetta di mostrarvi qualche caratteristica di Active Record.

La prima tabella che ho creato è stata quella per la 'testata' della Chat:


In Delphi ho definito una Entity che rappresentasse la tabella:

L'entity così definita è l'astrazione della tabella che abbiamo definito nel database.
Analizziamola:

dichiariamo una classe derivata da TMVCActiveRecord: 

TChats = class(TMVCActiveRecord)

TMVCActiveRecord è la classe base definita nel framework e che implementa tutti quei metodi utili alla
interazione con i dati.
La caratteristica principale che notiamo nella definizione della entity, riguarda i fields della classe. 
Ognuno di essi è 'decoratocon un Custom Attribute che ne determina il comportamento:

[MVCTable('chats')] :è il Custom Attribute che ci permette di definire il nome della tabella del DB di cui questa classe è astrazione;
[MVCTableField('chat_uuid', [foPrimaryKey])]: è il Custom Attribute utilizzato per 'legare' il field della classe all'attributo
della tabella fisica del database.

Per ogni tabella del database con la quale necessitiamo interagire, creeremo una entity.

A questo punto non ci resta che leggere il Json (utilizzo la libreria JsonDataObjects, anch'essa
disponibile in DMVCFramework), iterare su di esso e memorizzarlo nel DB:

Grazie a questo codice, avrò nel database un nuovo record.

Quel che mostrato sino ad ora è solo una semplice introduzione ad Active Record implementato in 
DMVCFramework.
E sicuramente non è esaustivo di tutte le peculiarità implementate.
Ad esempio: come faccio a sapere se la chat che sto analizzando è stata già elaborata precendentemente?

In questo esempio ho utilizzato l'RQL (Resources Query Language), ma avrei potuto anche utilizzare un 
metodo di Active Record che, ad esempio, mi permette di interrogare il db cercando per chiave primaria...

Questo esempio pratico dimostra come Active Record semplifichi notevolmente le operazioni di persistenza
dei dati, permettendoci di concentrarci sulla logica di business piuttosto che sui dettagli di implementazione
dell'accesso al database. 
La combinazione di DMVCFramework e il pattern Active Record ha reso il processo di importazione e 
gestione dei dati JSON estremamente fluido ed efficiente. È importante notare che, nonostante l'esempio mostrato sia relativamente semplice, Active Record 
in DMVCFramework supporta scenari molto più complessi, incluse relazioni tra entità, validazioni 
personalizzate e query avanzate.
Per chi volesse approfondire l'argomento, consiglio di esplorare la documentazione di DMVCFramework,
che offre molti altri esempi e casi d'uso avanzati del pattern Active Record.
La comprensione di questo pattern e la sua corretta implementazione possono significativamente migliorare
la produttività nello sviluppo di applicazioni Delphi che necessitano di interazione con database. #codinglikeacoder

venerdì 24 gennaio 2025

ITDevCon Spring Edition 2025

 Ci siamo: il conto alla rovescia per l'ITDevCon Spring Edition 2025 è iniziato!

Tutte le info per la partecipazione e, se volete, la Call4Paper è disponibile al link www.itdevcon.it.



#siateci

#codinglikeacoder

giovedì 16 gennaio 2025

[EN] Vectors & Features Extraction

At the recent ITDevCon in Rome, I introduced Vector Databases in my speech. 

The topic of Vectors and their use, especially for semantic search, has fascinated me since I first read about it. And even today, also in relation to my ongoing Machine Learning studies, Vectors continue to raise questions that I intend to answer (for myself).

For the benefit of those who will read this article, let's proceed in an orderly manner.

What are Vectors?

Vectors are "the multidimensional representation of an object."
Each dimension encodes specific information about the object and, together with others, contributes to the composition of the Embedding (another way to refer to the vector) of the object itself.
Taking up the example I proposed during my speech, let's consider the following sentence:

"L'ITDevCon è la conferenza su Delphi più attesa nell'anno"

Thanks to the use of an LLM model, we obtain the corresponding vector for this sentence:

As mentioned, each vector element encodes a semantic particularity (in this case) of the text.

For example:

Similarly, we would obtain such a vector in the case of an image, an email, a PDF, an audio track...
...and all this using specific models for text, images, audio, pre-trained and performant.

So far, so good: I pass text or an image to a transformer (BERT for text, ResNet for images) and get the embedding.

Let's now imagine one of those scenarios that we analyze daily; a scenario where there exists a classic RDBMS, supporting a business management system, where products are certainly stored. Products are at the center of business activity and, for many, many possible reasons, an embedding process is required for each of them for their management in a new business process where semantic search is fundamental.

Features
A product, generally, is a well-defined entity: it has a code, description, price, unit of measure, supplier, category, subcategory, image...
...but it also has correlations: it can be linked to other products as complementary; it has correlations on the type of use or its manufacture. It has specific behaviors. It has information about customer interactions (sales) or through social channels.

It has, to generalize, useful and necessary information for accurate and precise semantic search beyond all those characteristics (description, price...) that define it.

These informations are called Features.

Features cannot be ignored. And they particularly cannot be ignored when, as in this example case, products are subject to analysis and prediction through Machine Learning systems. Even if, in these cases, embedding might not be the ultimate goal.

Features and their extraction: a fundamental process
But how do we extract these features?

The process, called Feature Engineering, requires a deep understanding of both the application domain and data processing techniques. For example, from a review's text, we could extract the general sentiment (positive, negative), the most frequent keywords, the text length, the presence of specific technical terms (as seen in the previous example).

And let's not forget behavioral data: the number of times a product is viewed before purchase, the average time spent on its page, products viewed in the same session - these are all features that tell a story about the relationship between the product and the customer.

Feature extraction is not a simple process. Nor is it brief.

Feature extraction lies in balancing the quantity of information with their relevance. Not all features have the same weight, and part of the challenge lies in selecting those that best represent our object in the specific context in which we will use them.

In the embedding creation process, the features are then processed and transformed into those vector dimensions we talked about earlier, contributing to creating a rich and meaningful representation of our product.

The Challenge

The race towards 'Artificial Intelligence' by companies opens new scenarios for those who, like me, like us, design and develop software solutions for business. But it makes us vulnerable to failure when the proposed solution is not the result of real knowledge of the domain and the rules that the domain imposes.
It has always been and always will be this way: domain analysis is fundamental to our work.
And in the field of Artificial Intelligence, a very broad and technical subject, very far from everyday standards and often from our professional training up until now, pitfalls and failure are always just around the corner.
This is why we need to be aware that this is a field of action that must be approached with respect and humility. It's not just simple programming. It cannot be and should not be.

#codinglikeacoder

Vectors & Features Extraction

Allo scorso ITDevCon a Roma, con il mio speech ho introdotto i Vector Database. 
Quello dei Vettori e del loro utilizzo, specie per la ricerca semantica, è un argomento che mi ha appassionato sin da quando ne lessi la prima volta. E ancora oggi, anche in relazione allo studio del Machine Learning che sto facendo, i Vectors continuano a destarmi domande a cui intendo dare risposte (per me stesso). 

Anche in favore di coloro che leggeranno questo mio scritto, andiamo con ordine. 

 Cosa sono i Vettori?
 I Vettori sono "la rappresentazione multidimensionale di un oggetto". 
Ogni dimensione codifica informazioni specifiche dell'oggetto e, aggiungendosi alle altre, concorre alla composizione dell'Embedding (altro modo di riferirsi al vettore) dell'oggetto stesso. 
Riprendendo l'esempio che ho proposto durante il mio speech, consideriamo la seguente frase:

 "L'ITDevCon è la conferenza su Delphi più attesa nell'anno"

Grazie all'impiego di un modello LLM, otteniamo il vettore corrispondente a questa frase:


Come detto, ogni elemento del vettore, codifica una particolarità semantica (in questo caso) del testo.
Ad esempio:


In maniera analoga otterremmo un vettore siffatto anche nel caso di un immagine, una E-Mail, un PDF, una traccia audio.....
...e il tutto con l'impego di modelli specifici, per il testo, per le immagini, per l'audio, pre-addestrati e performanti.

Sin qui, tutto bello: passo del testo o una immagine ad un transformer (BERT per il testo, ResNet per le immagini) e ottengo l'embedding.

Proviamo adesso ad immaginare uno di quegli scenari che giornalmente ci si trova ad analizzare; scenario in cui esiste un RDMS classico (Postgres, Firebird...), a supporto di un gestionale aziendale, dove sicuramente vi sono memorizzati prodotti. I prodotti sono il centro dell'attività aziendale e, per tanti, tantissimi possibili motivi, è richiesto un processo di embedding di ognuno di essi al fine di una loro gestione in un nuovo processo aziendale in cui la ricerca semantica è fondamentale.

Le Features
Un prodotto, in genere, è una entity ben definita: ha un codice, una descrizione, un prezzo, una unità di misura, un fornitore, una categoria, una sub categoria, una immagine......
...ma ha anche delle correlazioni: può essere collegato ad altri prodotti in quanto complementari; ha delle correlazioni sul tipo di impiego o sulla sua fattura. Ha comportamenti specifici. Ha informazioni sull'interazione coi clienti (vendite) o attraverso i canali social.
Ha, per generalizzare, informazioni utili e necessarie per una semantic search corretta e puntuale oltre a tutte quelle info (descrizione, prezzo....) che lo caratterizzano.
Tali informazioni, attributi e correlazioni,  sono dette Features.
Le Features non possono essere ignorate. E non possono essere ignorate in particolare quando, come in questo caso esempflicativo, i  prodotti sono oggetto di analisi e predizione tramite sistemi di Machine Learning. Anche se, in questi casi, l'embedding potrebbe non essere  il fine ultimo.

Le Features e la loro estrazione: un processo fondamentale
Ma come estraiamo queste features? 
Il processo, chiamato Feature Engineering, richiede una profonda comprensione sia del dominio applicativo che delle tecniche di elaborazione dati. Ad esempio, dal testo di una recensione potremmo estrarre il sentiment generale (positivo, negativo),  le parole chiave più frequenti,  la lunghezza del testo, la presenza di termini tecnici specifici (come visto nell'esempio precedente)
E non dimentichiamo i dati comportamentali: il numero di volte che un prodotto viene visualizzato prima dell'acquisto, il tempo medio speso sulla sua pagina, i prodotti visualizzati nella stessa sessione: sono tutte features che raccontano una storia sulla relazione tra il prodotto e il cliente.

L'estrazione delle features non è un processo semplice. Nè tanto meno breve.

L'estrazione delle features sta nel bilanciare la quantità di informazioni con la loro rilevanza. Non tutte le features hanno lo stesso peso, e parte della sfida sta proprio nel selezionare quelle che meglio rappresentano il nostro oggetto nel contesto specifico in cui andremo ad utilizzarle.
Nel processo di creazione dell'embedding, le features vengono poi elaborate e trasformate in quelle dimensioni vettoriali di cui parlavamo prima, contribuendo a creare una rappresentazione ricca e significativa del nostro prodotto.

La Sfida
La corsa alla 'Intelligenza Artificiale' da parte delle aziende apre nuovi scenari per chi come me, come noi, progetta e sviluppa soluzioni software per il business. Ma ci rende vulnerabili al fallimento quando la soluzione proposta non è il frutto di conoscenza reale del dominio e delle regole che il dominio impone. 
E' sempre così e sempre lo sarà: l'analisi del dominio è fondamentale per il nostro lavoro.
E nell'ambito della Intelligenza Artificiale, materia molto ampia e molto tecnica, molto lontana dai canoni quotidiani e spesso dalla nostra formazione professionale sino ad oggi, l'insidia e il fallimento sono sempre dietro l'angolo.
E' per questo che è necessario essere coscienti che questo è un ambito di azione a cui approcciarsi con rispetto e umiltà. Non è semplice programmazione. Non lo può essere e non lo deve essere.

#codinglikeacoder

mercoledì 2 ottobre 2024

[EN] ITDevCon bites 2024

 ITDevCon Bites!






📌 Tuesday 8 October, 2.00 pm - Milan c/o Estensya, Via San Gregorio 55

💥 FREE

ITDevCon Bites is a short, half-day edition, designed to give companies and professionals from the north the opportunity to have a taste of the actual conference. 

Interesting talks on the theme of Delphi and its surroundings await you!

What are you waiting for? Register now for free ➡https://bit.ly/3XPOag9

[IT] ITDevCon bites 2024

 Ci vediamo a Milano, l'8 Ottobre!


ITDevCon Bites!

📌 Martedì 8 ottobre, ore 14.00 - Milano c/o Estensya, Via San Gregorio 55
💥 GRATUITO
ITDevCon Bites è un’edizione breve, di mezza giornata, pensata per dare l’opportunità ad aziende e professionisti del nord di avere un assaggio della conferenza vera e propria. 
Interessanti speech a tema Delphi e dintorni ti aspettano!
Cosa aspetti? Registrati ora gratis ➡https://bit.ly/3XPOag9





[EN] DMVCFramework Gotcha #2: Active Record

Active Record is an architectural design pattern introduced by Martin Fowler in his 2003 publication. The Active Record pattern is built on ...