This is a web application designed to make medical instructions more accessible and easy to follow. Leveraging the capabilities of a Google Gemini Large Language Model (LLM), the app takes raw medical text input (typed manually or extracted from images/PDFs) and transforms it into an understandable format, accompanied by a gentle narrative story for easier memorization and a practical integration with Google Calendar.
* Flexible Input: Enter medical instructions directly via a text box or upload an image (JPEG, PNG, WEBP) or a PDF document. The app uses OCR (Optical Character Recognition) via the Gemini API to automatically extract the text from these files. * Structured Summary: The medical text is processed to generate a clear and concise Markdown table that summarizes the medications, their dosage, the important time for intake, and the reason for taking them. * Smart Calendar Reminders: Each medication and its time are transformed into a calendar event. The app offers the option to individually add these reminders to Google Calendar, with a pre-configured daily frequency, facilitating adherence to the therapy. * Gentle Story: To help recall the instructions in a more creative and less intimidating way, the LLM generates a short narrative story. This story is designed to be reassuring and suitable for all ages, including the elderly and children. * Text-to-Speech (TTS): Listen to the story generated by the LLM thanks to integration with the browser's speech synthesis, making the experience more accessible and engaging. * Intuitive User Interface: A clean and responsive design based on Tailwind CSS ensures a pleasant user experience on devices of different sizes. * Status Feedback: Clear visual indicators show the processing status (loading, success, error) to keep the user informed.
The application is developed in React and utilizes the following functionalities:
* React: For building the interactive user interface.
* Google Gemini API (@google/genai): The core intelligence of the app. It is used for:
* Text Extraction: The gemini-2.5-flash (multi-modal) model is employed for OCR from images and PDFs.
* Reminder Generation: The gemini-2.5-flash model is used to transform medical text into a structured summary, a Markdown table, and the story. The responseSchema configuration ensures the output is consistent and predictable JSON.
* Speech Synthesis API (Browser): Used to convert the story into audio, with support for the Italian language.
* Google Calendar API (Via URL): Integration is done by generating pre-populated URLs for event creation, which the user can open and confirm directly in their Google Calendar.
* Tailwind CSS: For quick and customizable styling.
* react-markdown and remark-gfm: For rendering the Markdown tables generated by the LLM.
To run this application locally, you will need:
- Node.js (version 18 or higher) installed on your computer.
- A Google Gemini API key. You can get one for free from Google AI Studio.
- The API key must be configured as an environment variable named API_KEY in your execution environment.
1. Clone the Project
bash git clone [https://github.com/your-user/medimente.git](https://github.com/your-user/medimente.git) cd medimente
2. Install Dependencies
bash npm install
This command will install the local web server (serve) and all React dependencies.
3. Configure Your API Key
The application automatically retrieves the API key from the environment variable process.env.API_KEY.
You do not need to modify any code files (like config.ts or config.js) to configure the API key.
To run the app locally, ensure the environment variable API_KEY is set before starting the server. You can do this in several ways:
* Temporarily in the terminal (for current session):
bash export API_KEY='YOUR_API_KEY' # Linux/macOS set API_KEY='YOUR_API_KEY' # Windows (CMD) $env:API_KEY='YOUR_API_KEY' # Windows (PowerShell)
* Using a .env file (requires dotenv or similar configurations, not included by default in this simple setup): If you wanted a .env file, you would need to install and configure the dotenv library. For this project, it is assumed that the environment variable is already present in the execution environment.
After installing the dependencies and configuring the API key, start the application with:
npm startThe terminal will show you a local address, usually http://localhost:3000. Open this address in your web browser to use the application.
This configuration is intended exclusively for local development and demonstration.
DO NOT deploy this application to a public server (such as Netlify, Vercel, GitHub Pages, etc.) without first implementing a secure backend. Making direct calls to the Gemini API from the browser would expose your API key to anyone inspecting the source code, with possible consequences such as unexpected costs or abuse. For a public deployment, calls to the Gemini API must be mediated by a backend server that keeps the API key hidden.
This application, in its current form, demonstrates the potential of LLMs to simplify medical information. However, the true impact could be achieved by integrating with existing healthcare standards and systems such as HL7 FHIR (Fast Healthcare Interoperability Resources) and the Fascicolo Sanitario Elettronico (FSE) (Electronic Health Record - EHR).
* Interoperability: Ensuring health data can be exchanged and understood across different systems. * Data Accuracy: Reducing manual errors and providing medical information directly from reliable sources. * Improved User Experience: Automating data input and further personalizing reminders. * Therapeutic Adherence: Providing more effective tools to help patients follow prescriptions.
1. Direct Data Input from FHIR/FSE:
* Authentication: Implement a secure authentication flow (e.g., OAuth 2.0 / OpenID Connect) to allow users (patients or healthcare providers) to access their FSE or an FHIR server.
* FHIR Queries: The app could query FHIR resources such as MedicationRequest (active prescriptions), MedicationStatement (medications taken by the patient), Patient (demographic information), Condition (diagnoses) to automatically obtain the patient's medication list.
* Elimination of OCR: With structured data directly from FHIR, the OCR process from images/PDFs could become redundant or only be used for unstructured reports.
2. Output and Update of the FSE:
* FHIR Resource Generation: The LLM could not only simplify instructions but also suggest the creation or updating of FHIR resources (e.g., a Communication for the simplified reminder, or an updated CarePlan with the explained instructions).
* Push of Reminders: In an authorized clinical context, the app could be capable of sending the simplified reminders directly into the patient's FSE, making them available to other healthcare providers and authorized family members.
3. Advanced Personalization:
* Clinical Context: Using information from FHIR resources such as Patient (age, preferred language), Condition (chronic conditions), and AllergyIntolerance (known allergies), the LLM could generate even more personalized and relevant stories and reminders, adapting the language and examples to the patient's specific context.
* Drug Interactions: If the app had access to MedicationKnowledge or other clinical decision support services, it could integrate warnings about potential drug interactions into the simplified summary.
4. Decision Support for Healthcare Providers: * Patient Simplification: Healthcare providers could use the app to quickly generate simplified instructions to give to patients, improving understanding and adherence. * Improved Documentation: The structured output could be useful for documentation in the FSE, ensuring instructions are clear and standardized.
Integration with FHIR and FSE would transform this demo into a powerful and secure tool, capable of interacting with the digital health ecosystem for more efficient and patient-centered care.
Contributions are welcome! If you have ideas to improve this app, feel free to open an issue or a pull request.
The app is designed by Marco Pingitore.
# MediMente
Questa è un'applicazione web progettata per rendere le istruzioni mediche più accessibili e facili da seguire. Utilizzando le capacità di un Large Language Model (LLM) di Google Gemini, l'app prende in input testo medico grezzo (digitato manualmente o estratto da immagini/PDF) e lo trasforma in un formato comprensibile, accompagnato da una storiella gentile per facilitare la memorizzazione e una pratica integrazione con Google Calendar.
## Caratteristiche Principali
* **Input Flessibile:** Inserisci le istruzioni mediche direttamente tramite una casella di testo o carica un'immagine (JPEG, PNG, WEBP) o un documento PDF. L'app utilizza l'OCR (Optical Character Recognition) tramite l'API di Gemini per estrarre automaticamente il testo da questi file.
* **Riassunto Strutturato:** Il testo medico viene elaborato per generare una tabella Markdown chiara e concisa che riassume i farmaci, il loro dosaggio, l'orario importante per l'assunzione e il motivo per cui vengono presi.
* **Promemoria Calendario Intelligenti:** Ogni farmaco e il suo orario vengono trasformati in un evento del calendario. L'app offre la possibilità di aggiungere singolarmente questi promemoria a Google Calendar, con una frequenza giornaliera pre-configurata, facilitando l'aderenza alla terapia.
* **Storiella Gentile:** Per aiutare a ricordare le istruzioni in modo più creativo e meno intimidatorio, l'LLM genera una breve storiella narrativa. Questa storiella è pensata per essere rassicurante e adatta a un pubblico di tutte le età, inclusi anziani e bambini.
* **Sintesi Vocale (TTS):** Ascolta la storiella generata dall'LLM grazie all'integrazione con la sintesi vocale del browser, rendendo l'esperienza più accessibile e coinvolgente.
* **Interfaccia Utente Intuitiva:** Un design pulito e reattivo basato su Tailwind CSS garantisce un'esperienza utente piacevole su dispositivi di diverse dimensioni.
* **Feedback di Stato:** Indicatori visivi chiari mostrano lo stato dell'elaborazione (caricamento, successo, errore) per tenere l'utente sempre informato.
## Architettura e Componenti Chiave
L'applicazione è sviluppata in React e utilizza le seguenti funzionalità:
* **React:** Per la costruzione dell'interfaccia utente interattiva.
* **Google Gemini API (`@google/genai`):** Il cuore dell'intelligenza dell'app. Viene utilizzato per:
* **Estrazione Testo:** Il modello `gemini-2.5-flash` (multi-modale) è impiegato per l'OCR da immagini e PDF.
* **Generazione Promemoria:** Il modello `gemini-2.5-flash` viene usato per trasformare il testo medico in un riassunto strutturato, una tabella Markdown e la storiella. La configurazione `responseSchema` assicura che l'output sia un JSON coerente e predicibile.
* **Speech Synthesis API (Browser):** Utilizzata per convertire la storiella in audio, con supporto per la lingua italiana.
* **Google Calendar API (Tramite URL):** L'integrazione avviene generando URL pre-popolati per la creazione di eventi, che l'utente può aprire e confermare direttamente nel proprio Google Calendar.
* **Tailwind CSS:** Per uno styling rapido e personalizzabile.
* **`react-markdown` e `remark-gfm`:** Per il rendering delle tabelle Markdown generate dall'LLM.
## Prerequisiti
Per eseguire questa applicazione localmente, avrai bisogno di:
- [Node.js](https://nodejs.org/) (versione 18 o superiore) installato sul tuo computer.
- Una **chiave API di Google Gemini**. Puoi ottenerne una gratuitamente da [Google AI Studio](https://aistudio.google.com/app/apikey).
- La chiave API deve essere configurata come variabile d'ambiente chiamata `API_KEY` nel tuo ambiente di esecuzione.
## Configurazione
1. **Clona il Progetto**
```bash
git clone https://github.com/tuo-utente/medimente.git
cd medimente
```
2. **Installa le Dipendenze**
```bash
npm install
```
Questo comando installerà il server web locale (`serve`) e tutte le dipendenze di React.
3. **Configura la Tua Chiave API**
L'applicazione preleva automaticamente la chiave API dalla variabile d'ambiente `process.env.API_KEY`.
**Non è necessario modificare alcun file di codice (come `config.ts` o `config.js`) per configurare la chiave API.**
Per eseguire l'app localmente, assicurati che la variabile d'ambiente `API_KEY` sia impostata prima di avviare il server. Puoi farlo in diversi modi:
* **Temporaneamente nel terminale (per sessione corrente):**
```bash
export API_KEY='LA_TUA_CHIAVE_API' # Linux/macOS
set API_KEY='LA_TUA_CHIAVE_API' # Windows (CMD)
$env:API_KEY='LA_TUA_CHIAVE_API' # Windows (PowerShell)
```
* **Usando un file `.env` (richiede `dotenv` o configurazioni simili, non incluso di default in questo setup semplice):** Se volessi un file `.env`, dovresti installare e configurare la libreria `dotenv`. Per questo progetto, si assume che la variabile d'ambiente sia già presente nell'ambiente di esecuzione.
## Come Eseguire l'App
Dopo aver installato le dipendenze e configurato la chiave API, avvia l'applicazione con:
```bash
npm start
Il terminale ti mostrerà un indirizzo locale, solitamente http://localhost:3000. Apri questo indirizzo nel tuo browser web per usare l'applicazione.
Questa configurazione è pensata esclusivamente per lo sviluppo e la dimostrazione in locale.
NON distribuire questa applicazione su un server pubblico (come Netlify, Vercel, GitHub Pages, ecc.) senza prima implementare un backend sicuro. Effettuare chiamate dirette all'API di Gemini dal browser esporrebbe la tua chiave API a chiunque ispezioni il codice sorgente, con possibili conseguenze come costi inattesi o abusi. Per una distribuzione pubblica, le chiamate all'API di Gemini devono essere mediate da un server lato backend che mantenga la chiave API nascosta.
Questa applicazione, nella sua forma attuale, dimostra il potenziale degli LLM per semplificare le informazioni mediche. Tuttavia, il vero impatto potrebbe essere raggiunto integrandosi con gli standard e i sistemi sanitari esistenti come HL7 FHIR (Fast Healthcare Interoperability Resources) e il Fascicolo Sanitario Elettronico (FSE).
- Interoperabilità: Garantire che i dati sanitari possano essere scambiati e compresi tra diversi sistemi.
- Accuratezza dei Dati: Ridurre gli errori manuali e fornire informazioni mediche direttamente da fonti affidabili.
- Esperienza Utente Migliorata: Automatizzare l'input dei dati e personalizzare ulteriormente i promemoria.
- Aderenza Terapeutica: Fornire strumenti più efficaci per aiutare i pazienti a seguire le prescrizioni.
-
Input Dati Diretti da FHIR/FSE:
- Autenticazione: Implementare un flusso di autenticazione sicuro (es. OAuth 2.0 / OpenID Connect) per consentire agli utenti (pazienti o operatori sanitari) di accedere al proprio FSE o a un server FHIR.
- Query FHIR: L'app potrebbe interrogare risorse FHIR come
MedicationRequest(prescrizioni attive),MedicationStatement(farmaci assunti dal paziente),Patient(informazioni demografiche),Condition(diagnosi) per ottenere automaticamente l'elenco dei farmaci del paziente. - Eliminazione OCR: Con i dati strutturati direttamente da FHIR, il processo di OCR da immagini/PDF potrebbe diventare superfluo o essere utilizzato solo per referti non strutturati.
-
Output e Aggiornamento del FSE:
- Generazione di Risorse FHIR: L'LLM potrebbe non solo semplificare le istruzioni, ma anche suggerire la creazione o l'aggiornamento di risorse FHIR (es. un
Communicationper il promemoria semplificato, o unCarePlanaggiornato con le istruzioni spiegate). - Push di Promemoria: In un contesto clinico autorizzato, l'app potrebbe essere in grado di inviare i promemoria semplificati direttamente nel FSE del paziente, rendendoli disponibili anche ad altri operatori sanitari e ai familiari autorizzati.
- Generazione di Risorse FHIR: L'LLM potrebbe non solo semplificare le istruzioni, ma anche suggerire la creazione o l'aggiornamento di risorse FHIR (es. un
-
Personalizzazione Avanzata:
- Contesto Clinico: Utilizzando informazioni da risorse FHIR come
Patient(età, lingua preferita),Condition(patologie croniche) eAllergyIntolerance(allergie note), l'LLM potrebbe generare storiella e promemoria ancora più personalizzati e rilevanti, adattando il linguaggio e gli esempi al contesto specifico del paziente. - Interazioni Farmacologiche: Se l'app avesse accesso a
MedicationKnowledgeo ad altri servizi di supporto decisionale clinico, potrebbe integrare avvisi su potenziali interazioni farmacologiche nel riassunto semplificato.
- Contesto Clinico: Utilizzando informazioni da risorse FHIR come
-
Supporto Decisionale per Operatori Sanitari:
- Semplificazione per il Paziente: Gli operatori sanitari potrebbero utilizzare l'app per generare rapidamente istruzioni semplificate da consegnare ai pazienti, migliorando la comprensione e l'aderenza.
- Documentazione Migliorata: L'output strutturato potrebbe essere utile per la documentazione nel FSE, garantendo che le istruzioni siano chiare e standardizzate.
L'integrazione con FHIR e FSE trasformerebbe questa demo in uno strumento potente e sicuro, capace di dialogare con l'ecosistema sanitario digitale per un'assistenza al paziente più efficiente e centrata.
I contributi sono benvenuti! Se hai idee per migliorare questa app, sentiti libero di aprire una issue o una pull request.
L'app è progettata da Marco Pingitore.