File size: 4,894 Bytes
51ae1fa
 
 
 
 
 
 
97bf541
 
 
 
 
 
 
 
 
51ae1fa
 
 
 
 
97bf541
 
 
 
51ae1fa
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6f29d77
51ae1fa
 
 
 
 
 
 
 
 
 
 
183bdd3
97bf541
183bdd3
97bf541
72f344e
183bdd3
97bf541
183bdd3
97bf541
183bdd3
 
51ae1fa
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
import gradio as gr
from transformers import pipeline
from huggingface_hub import login
import os

# Initialize global pipeline
ner_pipeline = None

# Authenticate using the secret `HFTOKEN`
def authenticate_with_token():
    """Authenticate with the Hugging Face API using the HFTOKEN secret."""
    hf_token = os.getenv("HFTOKEN")  # Retrieve the token from environment variables
    if not hf_token:
        raise ValueError("HFTOKEN is not set. Please add it to the Secrets in your Space settings.")
    login(token=hf_token)

    
def load_healthcare_ner_pipeline():
    """Load the Hugging Face pipeline for Healthcare NER."""
    global ner_pipeline
    if ner_pipeline is None:        
        
        # Authenticate and initialize pipeline
        authenticate_with_token()
        
        ner_pipeline = pipeline(
            "token-classification",
            model="TypicaAI/magbert-ner",
            aggregation_strategy="first"  # Groups B- and I- tokens into entities
        )
    return ner_pipeline


def process_text(text):
    """Process input text and return highlighted entities."""
    pipeline = load_healthcare_ner_pipeline()
    entities = pipeline(text)
    return {"text": text, "entities": entities}


def log_demo_usage(text, num_entities):
    """Log demo usage for analytics."""
    print(f"Processed text: {text[:50]}... | Entities found: {num_entities}")

# Define the main demo interface
demo = gr.Interface(
    fn=process_text,
    inputs=gr.Textbox(
        label="Paste French text",
        placeholder="La Coupe du monde de football 2030 se déroulera au Maroc, en Espagne et au Portugal.",
        lines=5
    ),
    outputs=gr.HighlightedText(label="Identified Entities"),
    title="🌟 MagBERT-NER: High-Performing French NER",
    description="""
    _By **[Hicham Assoudi](https://huggingface.co./hassoudi)** – AI Researcher (Ph.D.), Oracle Consultant, and Author._ 🔗 [Follow me on LinkedIn](https://www.linkedin.com/in/assoudi)
    
    MagBERT-NER is a robust **Named Entity Recognition (NER)** model for the **French language**, trained on a manually curated dataset from diverse Moroccan sources. It’s designed to handle names, places, currencies, and other entities with exceptional precision, especially in **Moroccan contexts**.  
    ## 🚀 Highlights:  
    - **20,000+ Downloads**: Trusted by developers and researchers for French NER tasks.  
    - **🌐 Recognized by John Snow Labs**: Adapted for scalability and enterprise-grade applications like **healthcare**.
    """,
    article="""
    ## ⚠️ Disclaimer
    This is a **free demo model** provided without support. While it showcases high precision and is ideal for educational and exploratory purposes, it is not intended for production or commercial use.  

    For production-grade or commercial models, please contact us at **[email protected]**.
    """,
    examples=[
        ["Fatima Zahra et Youssef ont discuté du projet Al Amal à Rabat pendant Ramadan et ont alloué un budget de 50 000 dirhams pour les artisans locaux."],
        ["Hassan et Jean ont visité la zone industrielle de Settat avant de se rendre à Toulouse, à l’usine d’Airbus, pour discuter d’un contrat de 5 millions d’euros."],
        ["L'association Noor, basée à Marrakech, a organisé un atelier en septembre pour former des femmes sur les techniques de tissage, avec un financement de 20 000 dirhams."],
        ["L’association Amal, basée à Tanger, a collaboré avec l’UNICEF à Genève pour un programme de soutien aux écoles rurales, avec un budget de 1,5 million de dollars."],
        ["Fatima et Michael ont participé à une réunion à Casablanca pour le projet Green Energy, financé par une banque suisse à hauteur de 2 millions DHS."],
        ["Khalid a rencontré Salma au café Bab Al Madina à Fès pour discuter du festival Al Maghrib, qui aura lieu en octobre avec un budget de 100 000 dirhams."],
        ["Youssef et Sarah ont signé un accord à Rabat avec IBM et une start-up Canadienne pour développer des solutions AI destinées au marché africain."],
        ["La société Zainab Artisans a ouvert une boutique à Casablanca en mars, où elle propose des produits faits main, notamment des bijoux et des tapis pour 5 000 à 20 000 dirhams."],
        ["Lors du Forum économique à Marrakech, Khalid a rencontré des représentants d’Amazon à Seattle et d’OCP Group pour un partenariat évalué à 20 millions de dirhams."],
        ["L'association Rif Talents, basée à Al Hoceima, a annoncé une bourse de 15 000 dirhams pour les jeunes artistes peintres lors du Festival du Zellige."],
        ["Jean-Luc et Youssef ont dîné au restaurant Le Kasbah à Chefchaouen, discutant d’une exposition sur la poterie berbère prévue à El Hajeb."],    ]
)

# Launch the Gradio demo
if __name__ == "__main__":
    demo.launch()