######################################################################### # Copyright (C) # # 2025-June Sen Li (Sen.Li.Sprout@gmail.com) # # Permission given to modify the code only for Non-Profit Research # # as long as you keep this declaration at the top # ######################################################################### import os import gradio as gr import huggingface_hub import sentence_transformers # ---------------------------------------------------------------------------------------------------------------------- def func_ClearInputs(): return "", "", "" def func_sBERT_SimilarityResult(str_Text_1, str_Text_2): if not str_Text_1.strip() or not str_Text_2.strip(): return "Both text inputs must be non-empty." # 01. Load SBERT model (you can choose other pre-trained models too) inferenceClient = huggingface_hub.InferenceClient(provider="hf-inference") # 02. Get sentence embeddings str_ModelID_sBERT = "sentence-transformers/all-MiniLM-L6-v2" arrEmbedding_Text_1 = inferenceClient.feature_extraction(text=str_Text_1, model=str_ModelID_sBERT) arrEmbedding_Text_2 = inferenceClient.feature_extraction(text=str_Text_2, model=str_ModelID_sBERT) # 03. Compute cosine similarity tensor_Similarity = sentence_transformers.util.pytorch_cos_sim(arrEmbedding_Text_1, arrEmbedding_Text_2) f_Similarity = tensor_Similarity.item() return f"sBERT Similarity Score: {f_Similarity:.4f}" # ---------------------------------------------------------------------------------------------------------------------- # Launch the interface and MCP server if __name__ == "__main__": print(f"os.getcwd() = {os.getcwd()}") os.system(f"echo ls -al {os.getcwd()} && ls -al {os.getcwd()}") os.system(f"echo ls -al /: && ls -al /") os.system(f"echo ls -al /home/: && ls -al /home/") # 03. Gradio UI elements with gr.Blocks() as grBlocks_SentenceSimilarity__MCP_Server: gr.Markdown("# Sentence-BERT (sBERT) for Text Similarity using HF Inference Server") gr.Markdown("### This MCP-Server works for MCP-Client https://huggingface.co/spaces/AllIllusion/MCP-Client_SyntheticText_Similarity") gr.Markdown("This application calculates sBERT Similarity Score between two Texts") with gr.Row(): grTextBox_Input_1 = gr.Textbox(label="Text Panel 1", lines=20) grTextBox_Input_2 = gr.Textbox(label="Text Panel 2", lines=20) with gr.Row(): with gr.Column(scale=1): grButton_Clear = gr.Button("Clear") grButton_Submit = gr.Button("Submit") with gr.Column(scale=3): grTextbox_Output = gr.Textbox(label="Similarity Result", interactive=False) # Set button functionality grButton_Submit.click(fn=func_sBERT_SimilarityResult, inputs=[grTextBox_Input_1, grTextBox_Input_2], outputs=grTextbox_Output) grButton_Clear.click(fn=func_ClearInputs, inputs=[], outputs=[grTextBox_Input_1, grTextBox_Input_2, grTextbox_Output]) # 04. Launch Gradio MCP server grBlocks_SentenceSimilarity__MCP_Server.launch(mcp_server=True, share=True)