We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Add sentence similarity for spaCy
Computing similarity is simple with `spaCy` and there is an existing [template pipeline](https://github.com/huggingface/huggingface_hub/blob/main/api-inference-community/docker_images/common/app/pipelines/sentence_similarity.py) for sentence similarity at which can be modified for this. 

https://spacy.io/api/doc#similarity

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `api-inference-community/docker_images/spacy/app/pipelines/sentence_similarity.py`
Content:
```
1 from typing import Dict, List, Union
2 
3 from app.pipelines import Pipeline
4 
5 
6 class SentenceSimilarityPipeline(Pipeline):
7     def __init__(
8         self,
9         model_id: str,
10     ):
11         # IMPLEMENT_THIS
12         # Preload all the elements you are going to need at inference.
13         # For instance your model, processors, tokenizer that might be needed.
14         # This function is only called once, so do all the heavy processing I/O here
15         raise NotImplementedError(
16             "Please implement SentenceSimilarityPipeline __init__ function"
17         )
18 
19     def __call__(self, inputs: Dict[str, Union[str, List[str]]]) -> List[float]:
20         """
21         Args:
22             inputs (:obj:`dict`):
23                 a dictionary containing two keys, 'source_sentence' mapping
24                 to the sentence that will be compared against all the others,
25                 and 'sentences', mapping to a list of strings to which the
26                 source will be compared.
27         Return:
28             A :obj:`list` of floats: Some similarity measure between `source_sentence` and each sentence from `sentences`.
29         """
30         # IMPLEMENT_THIS
31         raise NotImplementedError(
32             "Please implement SentenceSimilarityPipeline __call__ function"
33         )
34
```

Path: `api-inference-community/docker_images/spacy/app/main.py`
Content:
```
1 import functools
2 import logging
3 import os
4 from typing import Dict, Type
5 
6 from api_inference_community.routes import pipeline_route, status_ok
7 from app.pipelines import (
8     Pipeline,
9     TextClassificationPipeline,
10     TokenClassificationPipeline,
11 )
12 from starlette.applications import Starlette
13 from starlette.middleware import Middleware
14 from starlette.middleware.gzip import GZipMiddleware
15 from starlette.routing import Route
16 
17 
18 TASK = os.getenv("TASK")
19 MODEL_ID = os.getenv("MODEL_ID")
20 
21 
22 logger = logging.getLogger(__name__)
23 
24 
25 # Add the allowed tasks
26 # Supported tasks are:
27 # - text-generation
28 # - text-classification
29 # - token-classification
30 # - translation
31 # - summarization
32 # - automatic-speech-recognition
33 # - ...
34 # For instance
35 # from app.pipelines import AutomaticSpeechRecognitionPipeline
36 # ALLOWED_TASKS = {"automatic-speech-recognition": AutomaticSpeechRecognitionPipeline}
37 # You can check the requirements and expectations of each pipelines in their respective
38 # directories. Implement directly within the directories.
39 ALLOWED_TASKS: Dict[str, Type[Pipeline]] = {
40     "token-classification": TokenClassificationPipeline,
41     "text-classification": TextClassificationPipeline,
42 }
43 
44 
45 @functools.lru_cache()
46 def get_pipeline() -> Pipeline:
47     task = os.environ["TASK"]
48     model_id = os.environ["MODEL_ID"]
49     if task not in ALLOWED_TASKS:
50         raise EnvironmentError(f"{task} is not a valid pipeline for model : {model_id}")
51     return ALLOWED_TASKS[task](model_id)
52 
53 
54 routes = [
55     Route("/{whatever:path}", status_ok),
56     Route("/{whatever:path}", pipeline_route, methods=["POST"]),
57 ]
58 
59 middleware = [Middleware(GZipMiddleware, minimum_size=1000)]
60 if os.environ.get("DEBUG", "") == "1":
61     from starlette.middleware.cors import CORSMiddleware
62 
63     middleware.append(
64         Middleware(
65             CORSMiddleware,
66             allow_origins=["*"],
67             allow_headers=["*"],
68             allow_methods=["*"],
69         )
70     )
71 
72 app = Starlette(routes=routes, middleware=middleware)
73 
74 
75 @app.on_event("startup")
76 async def startup_event():
77     logger = logging.getLogger("uvicorn.access")
78     handler = logging.StreamHandler()
79     handler.setFormatter(logging.Formatter("%(asctime)s - %(levelname)s - %(message)s"))
80     logger.handlers = [handler]
81 
82     # Link between `api-inference-community` and framework code.
83     app.get_pipeline = get_pipeline
84     try:
85         get_pipeline()
86     except Exception:
87         # We can fail so we can show exception later.
88         pass
89 
90 
91 if __name__ == "__main__":
92     try:
93         get_pipeline()
94     except Exception:
95         # We can fail so we can show exception later.
96         pass
97
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/api-inference-community/docker_images/spacy/app/main.py b/api-inference-community/docker_images/spacy/app/main.py
--- a/api-inference-community/docker_images/spacy/app/main.py
+++ b/api-inference-community/docker_images/spacy/app/main.py
@@ -6,6 +6,7 @@
 from api_inference_community.routes import pipeline_route, status_ok
 from app.pipelines import (
     Pipeline,
+    SentenceSimilarityPipeline,
     TextClassificationPipeline,
     TokenClassificationPipeline,
 )
@@ -30,6 +31,7 @@
 # - translation
 # - summarization
 # - automatic-speech-recognition
+# - sentence-similarity
 # - ...
 # For instance
 # from app.pipelines import AutomaticSpeechRecognitionPipeline
@@ -39,6 +41,7 @@
 ALLOWED_TASKS: Dict[str, Type[Pipeline]] = {
     "token-classification": TokenClassificationPipeline,
     "text-classification": TextClassificationPipeline,
+    "sentence-similarity": SentenceSimilarityPipeline,
 }
 
 
diff --git a/api-inference-community/docker_images/spacy/app/pipelines/sentence_similarity.py b/api-inference-community/docker_images/spacy/app/pipelines/sentence_similarity.py
--- a/api-inference-community/docker_images/spacy/app/pipelines/sentence_similarity.py
+++ b/api-inference-community/docker_images/spacy/app/pipelines/sentence_similarity.py
@@ -1,3 +1,6 @@
+import os
+import subprocess
+import sys
 from typing import Dict, List, Union
 
 from app.pipelines import Pipeline
@@ -8,14 +11,23 @@
         self,
         model_id: str,
     ):
-        # IMPLEMENT_THIS
-        # Preload all the elements you are going to need at inference.
-        # For instance your model, processors, tokenizer that might be needed.
-        # This function is only called once, so do all the heavy processing I/O here
-        raise NotImplementedError(
-            "Please implement SentenceSimilarityPipeline __init__ function"
+        # At the time, only public models from spaCy are allowed in the inference API.
+        full_model_path = model_id.split("/")
+        if len(full_model_path) != 2:
+            raise ValueError(
+                f"Invalid model_id: {model_id}. It should have a namespace (:namespace:/:model_name:)"
+            )
+        namespace, model_name = full_model_path
+        package = f"https://huggingface.co/{namespace}/{model_name}/resolve/main/{model_name}-any-py3-none-any.whl"
+        cache_dir = os.environ["PIP_CACHE"]
+        subprocess.check_call(
+            [sys.executable, "-m", "pip", "install", "--cache-dir", cache_dir, package]
         )
 
+        import spacy
+
+        self.model = spacy.load(model_name)
+
     def __call__(self, inputs: Dict[str, Union[str, List[str]]]) -> List[float]:
         """
         Args:
@@ -27,7 +39,12 @@
         Return:
             A :obj:`list` of floats: Some similarity measure between `source_sentence` and each sentence from `sentences`.
         """
-        # IMPLEMENT_THIS
-        raise NotImplementedError(
-            "Please implement SentenceSimilarityPipeline __call__ function"
-        )
+        source_sentence = inputs["source_sentence"]
+        source_doc = self.model(source_sentence)
+
+        similarities = []
+        for sentence in inputs["sentences"]:
+            search_doc = self.model(sentence)
+            similarities.append(source_doc.similarity(search_doc))
+
+        return similarities

{"golden_diff": "diff --git a/api-inference-community/docker_images/spacy/app/main.py b/api-inference-community/docker_images/spacy/app/main.py\n--- a/api-inference-community/docker_images/spacy/app/main.py\n+++ b/api-inference-community/docker_images/spacy/app/main.py\n@@ -6,6 +6,7 @@\n from api_inference_community.routes import pipeline_route, status_ok\n from app.pipelines import (\n     Pipeline,\n+    SentenceSimilarityPipeline,\n     TextClassificationPipeline,\n     TokenClassificationPipeline,\n )\n@@ -30,6 +31,7 @@\n # - translation\n # - summarization\n # - automatic-speech-recognition\n+# - sentence-similarity\n # - ...\n # For instance\n # from app.pipelines import AutomaticSpeechRecognitionPipeline\n@@ -39,6 +41,7 @@\n ALLOWED_TASKS: Dict[str, Type[Pipeline]] = {\n     \"token-classification\": TokenClassificationPipeline,\n     \"text-classification\": TextClassificationPipeline,\n+    \"sentence-similarity\": SentenceSimilarityPipeline,\n }\n \n \ndiff --git a/api-inference-community/docker_images/spacy/app/pipelines/sentence_similarity.py b/api-inference-community/docker_images/spacy/app/pipelines/sentence_similarity.py\n--- a/api-inference-community/docker_images/spacy/app/pipelines/sentence_similarity.py\n+++ b/api-inference-community/docker_images/spacy/app/pipelines/sentence_similarity.py\n@@ -1,3 +1,6 @@\n+import os\n+import subprocess\n+import sys\n from typing import Dict, List, Union\n \n from app.pipelines import Pipeline\n@@ -8,14 +11,23 @@\n         self,\n         model_id: str,\n     ):\n-        # IMPLEMENT_THIS\n-        # Preload all the elements you are going to need at inference.\n-        # For instance your model, processors, tokenizer that might be needed.\n-        # This function is only called once, so do all the heavy processing I/O here\n-        raise NotImplementedError(\n-            \"Please implement SentenceSimilarityPipeline __init__ function\"\n+        # At the time, only public models from spaCy are allowed in the inference API.\n+        full_model_path = model_id.split(\"/\")\n+        if len(full_model_path) != 2:\n+            raise ValueError(\n+                f\"Invalid model_id: {model_id}. It should have a namespace (:namespace:/:model_name:)\"\n+            )\n+        namespace, model_name = full_model_path\n+        package = f\"https://huggingface.co/{namespace}/{model_name}/resolve/main/{model_name}-any-py3-none-any.whl\"\n+        cache_dir = os.environ[\"PIP_CACHE\"]\n+        subprocess.check_call(\n+            [sys.executable, \"-m\", \"pip\", \"install\", \"--cache-dir\", cache_dir, package]\n         )\n \n+        import spacy\n+\n+        self.model = spacy.load(model_name)\n+\n     def __call__(self, inputs: Dict[str, Union[str, List[str]]]) -> List[float]:\n         \"\"\"\n         Args:\n@@ -27,7 +39,12 @@\n         Return:\n             A :obj:`list` of floats: Some similarity measure between `source_sentence` and each sentence from `sentences`.\n         \"\"\"\n-        # IMPLEMENT_THIS\n-        raise NotImplementedError(\n-            \"Please implement SentenceSimilarityPipeline __call__ function\"\n-        )\n+        source_sentence = inputs[\"source_sentence\"]\n+        source_doc = self.model(source_sentence)\n+\n+        similarities = []\n+        for sentence in inputs[\"sentences\"]:\n+            search_doc = self.model(sentence)\n+            similarities.append(source_doc.similarity(search_doc))\n+\n+        return similarities\n", "issue": "Add sentence similarity for spaCy\nComputing similarity is simple with `spaCy` and there is an existing [template pipeline](https://github.com/huggingface/huggingface_hub/blob/main/api-inference-community/docker_images/common/app/pipelines/sentence_similarity.py) for sentence similarity at which can be modified for this. \r\n\r\nhttps://spacy.io/api/doc#similarity\n", "before_files": [{"content": "from typing import Dict, List, Union\n\nfrom app.pipelines import Pipeline\n\n\nclass SentenceSimilarityPipeline(Pipeline):\n    def __init__(\n        self,\n        model_id: str,\n    ):\n        # IMPLEMENT_THIS\n        # Preload all the elements you are going to need at inference.\n        # For instance your model, processors, tokenizer that might be needed.\n        # This function is only called once, so do all the heavy processing I/O here\n        raise NotImplementedError(\n            \"Please implement SentenceSimilarityPipeline __init__ function\"\n        )\n\n    def __call__(self, inputs: Dict[str, Union[str, List[str]]]) -> List[float]:\n        \"\"\"\n        Args:\n            inputs (:obj:`dict`):\n                a dictionary containing two keys, 'source_sentence' mapping\n                to the sentence that will be compared against all the others,\n                and 'sentences', mapping to a list of strings to which the\n                source will be compared.\n        Return:\n            A :obj:`list` of floats: Some similarity measure between `source_sentence` and each sentence from `sentences`.\n        \"\"\"\n        # IMPLEMENT_THIS\n        raise NotImplementedError(\n            \"Please implement SentenceSimilarityPipeline __call__ function\"\n        )\n", "path": "api-inference-community/docker_images/spacy/app/pipelines/sentence_similarity.py"}, {"content": "import functools\nimport logging\nimport os\nfrom typing import Dict, Type\n\nfrom api_inference_community.routes import pipeline_route, status_ok\nfrom app.pipelines import (\n    Pipeline,\n    TextClassificationPipeline,\n    TokenClassificationPipeline,\n)\nfrom starlette.applications import Starlette\nfrom starlette.middleware import Middleware\nfrom starlette.middleware.gzip import GZipMiddleware\nfrom starlette.routing import Route\n\n\nTASK = os.getenv(\"TASK\")\nMODEL_ID = os.getenv(\"MODEL_ID\")\n\n\nlogger = logging.getLogger(__name__)\n\n\n# Add the allowed tasks\n# Supported tasks are:\n# - text-generation\n# - text-classification\n# - token-classification\n# - translation\n# - summarization\n# - automatic-speech-recognition\n# - ...\n# For instance\n# from app.pipelines import AutomaticSpeechRecognitionPipeline\n# ALLOWED_TASKS = {\"automatic-speech-recognition\": AutomaticSpeechRecognitionPipeline}\n# You can check the requirements and expectations of each pipelines in their respective\n# directories. Implement directly within the directories.\nALLOWED_TASKS: Dict[str, Type[Pipeline]] = {\n    \"token-classification\": TokenClassificationPipeline,\n    \"text-classification\": TextClassificationPipeline,\n}\n\n\n@functools.lru_cache()\ndef get_pipeline() -> Pipeline:\n    task = os.environ[\"TASK\"]\n    model_id = os.environ[\"MODEL_ID\"]\n    if task not in ALLOWED_TASKS:\n        raise EnvironmentError(f\"{task} is not a valid pipeline for model : {model_id}\")\n    return ALLOWED_TASKS[task](model_id)\n\n\nroutes = [\n    Route(\"/{whatever:path}\", status_ok),\n    Route(\"/{whatever:path}\", pipeline_route, methods=[\"POST\"]),\n]\n\nmiddleware = [Middleware(GZipMiddleware, minimum_size=1000)]\nif os.environ.get(\"DEBUG\", \"\") == \"1\":\n    from starlette.middleware.cors import CORSMiddleware\n\n    middleware.append(\n        Middleware(\n            CORSMiddleware,\n            allow_origins=[\"*\"],\n            allow_headers=[\"*\"],\n            allow_methods=[\"*\"],\n        )\n    )\n\napp = Starlette(routes=routes, middleware=middleware)\n\n\n@app.on_event(\"startup\")\nasync def startup_event():\n    logger = logging.getLogger(\"uvicorn.access\")\n    handler = logging.StreamHandler()\n    handler.setFormatter(logging.Formatter(\"%(asctime)s - %(levelname)s - %(message)s\"))\n    logger.handlers = [handler]\n\n    # Link between `api-inference-community` and framework code.\n    app.get_pipeline = get_pipeline\n    try:\n        get_pipeline()\n    except Exception:\n        # We can fail so we can show exception later.\n        pass\n\n\nif __name__ == \"__main__\":\n    try:\n        get_pipeline()\n    except Exception:\n        # We can fail so we can show exception later.\n        pass\n", "path": "api-inference-community/docker_images/spacy/app/main.py"}], "after_files": [{"content": "import os\nimport subprocess\nimport sys\nfrom typing import Dict, List, Union\n\nfrom app.pipelines import Pipeline\n\n\nclass SentenceSimilarityPipeline(Pipeline):\n    def __init__(\n        self,\n        model_id: str,\n    ):\n        # At the time, only public models from spaCy are allowed in the inference API.\n        full_model_path = model_id.split(\"/\")\n        if len(full_model_path) != 2:\n            raise ValueError(\n                f\"Invalid model_id: {model_id}. It should have a namespace (:namespace:/:model_name:)\"\n            )\n        namespace, model_name = full_model_path\n        package = f\"https://huggingface.co/{namespace}/{model_name}/resolve/main/{model_name}-any-py3-none-any.whl\"\n        cache_dir = os.environ[\"PIP_CACHE\"]\n        subprocess.check_call(\n            [sys.executable, \"-m\", \"pip\", \"install\", \"--cache-dir\", cache_dir, package]\n        )\n\n        import spacy\n\n        self.model = spacy.load(model_name)\n\n    def __call__(self, inputs: Dict[str, Union[str, List[str]]]) -> List[float]:\n        \"\"\"\n        Args:\n            inputs (:obj:`dict`):\n                a dictionary containing two keys, 'source_sentence' mapping\n                to the sentence that will be compared against all the others,\n                and 'sentences', mapping to a list of strings to which the\n                source will be compared.\n        Return:\n            A :obj:`list` of floats: Some similarity measure between `source_sentence` and each sentence from `sentences`.\n        \"\"\"\n        source_sentence = inputs[\"source_sentence\"]\n        source_doc = self.model(source_sentence)\n\n        similarities = []\n        for sentence in inputs[\"sentences\"]:\n            search_doc = self.model(sentence)\n            similarities.append(source_doc.similarity(search_doc))\n\n        return similarities\n", "path": "api-inference-community/docker_images/spacy/app/pipelines/sentence_similarity.py"}, {"content": "import functools\nimport logging\nimport os\nfrom typing import Dict, Type\n\nfrom api_inference_community.routes import pipeline_route, status_ok\nfrom app.pipelines import (\n    Pipeline,\n    SentenceSimilarityPipeline,\n    TextClassificationPipeline,\n    TokenClassificationPipeline,\n)\nfrom starlette.applications import Starlette\nfrom starlette.middleware import Middleware\nfrom starlette.middleware.gzip import GZipMiddleware\nfrom starlette.routing import Route\n\n\nTASK = os.getenv(\"TASK\")\nMODEL_ID = os.getenv(\"MODEL_ID\")\n\n\nlogger = logging.getLogger(__name__)\n\n\n# Add the allowed tasks\n# Supported tasks are:\n# - text-generation\n# - text-classification\n# - token-classification\n# - translation\n# - summarization\n# - automatic-speech-recognition\n# - sentence-similarity\n# - ...\n# For instance\n# from app.pipelines import AutomaticSpeechRecognitionPipeline\n# ALLOWED_TASKS = {\"automatic-speech-recognition\": AutomaticSpeechRecognitionPipeline}\n# You can check the requirements and expectations of each pipelines in their respective\n# directories. Implement directly within the directories.\nALLOWED_TASKS: Dict[str, Type[Pipeline]] = {\n    \"token-classification\": TokenClassificationPipeline,\n    \"text-classification\": TextClassificationPipeline,\n    \"sentence-similarity\": SentenceSimilarityPipeline,\n}\n\n\n@functools.lru_cache()\ndef get_pipeline() -> Pipeline:\n    task = os.environ[\"TASK\"]\n    model_id = os.environ[\"MODEL_ID\"]\n    if task not in ALLOWED_TASKS:\n        raise EnvironmentError(f\"{task} is not a valid pipeline for model : {model_id}\")\n    return ALLOWED_TASKS[task](model_id)\n\n\nroutes = [\n    Route(\"/{whatever:path}\", status_ok),\n    Route(\"/{whatever:path}\", pipeline_route, methods=[\"POST\"]),\n]\n\nmiddleware = [Middleware(GZipMiddleware, minimum_size=1000)]\nif os.environ.get(\"DEBUG\", \"\") == \"1\":\n    from starlette.middleware.cors import CORSMiddleware\n\n    middleware.append(\n        Middleware(\n            CORSMiddleware,\n            allow_origins=[\"*\"],\n            allow_headers=[\"*\"],\n            allow_methods=[\"*\"],\n        )\n    )\n\napp = Starlette(routes=routes, middleware=middleware)\n\n\n@app.on_event(\"startup\")\nasync def startup_event():\n    logger = logging.getLogger(\"uvicorn.access\")\n    handler = logging.StreamHandler()\n    handler.setFormatter(logging.Formatter(\"%(asctime)s - %(levelname)s - %(message)s\"))\n    logger.handlers = [handler]\n\n    # Link between `api-inference-community` and framework code.\n    app.get_pipeline = get_pipeline\n    try:\n        get_pipeline()\n    except Exception:\n        # We can fail so we can show exception later.\n        pass\n\n\nif __name__ == \"__main__\":\n    try:\n        get_pipeline()\n    except Exception:\n        # We can fail so we can show exception later.\n        pass\n", "path": "api-inference-community/docker_images/spacy/app/main.py"}]}