Spaces:
Running
Running
CyberFox commited on
Commit ·
38e7897
1
Parent(s): acfb4d1
Serve the canonical tag server-side: Gradio mounted on FastAPI, middleware writes rel=canonical into the index HTML
Browse files
app.py
CHANGED
|
@@ -581,5 +581,43 @@ with gr.Blocks(
|
|
| 581 |
)
|
| 582 |
|
| 583 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 584 |
if __name__ == "__main__":
|
| 585 |
-
|
|
|
|
| 581 |
)
|
| 582 |
|
| 583 |
|
| 584 |
+
# Gradio injects ``head`` client-side, so the canonical only exists after the
|
| 585 |
+
# JavaScript has run. Google honours that, but not reliably, and the point of
|
| 586 |
+
# the tag is to tell Google that https://wordlift.io/entity-extraction/ is the
|
| 587 |
+
# page. So the app is mounted on a FastAPI app whose middleware writes the tag
|
| 588 |
+
# into the HTML of the index page server-side; the hf.space copy then carries
|
| 589 |
+
# it in the raw response.
|
| 590 |
+
def _serve_with_canonical(port: int = 7860) -> None:
|
| 591 |
+
import uvicorn
|
| 592 |
+
from fastapi import FastAPI
|
| 593 |
+
from starlette.middleware.base import BaseHTTPMiddleware
|
| 594 |
+
from starlette.responses import Response
|
| 595 |
+
|
| 596 |
+
class CanonicalMiddleware(BaseHTTPMiddleware):
|
| 597 |
+
async def dispatch(self, request, call_next):
|
| 598 |
+
index = request.url.path in ("", "/")
|
| 599 |
+
if index:
|
| 600 |
+
# Ask the app for plain HTML so the tag can be inserted.
|
| 601 |
+
request.scope["headers"] = [
|
| 602 |
+
(k, v) for k, v in request.scope["headers"] if k != b"accept-encoding"
|
| 603 |
+
]
|
| 604 |
+
response = await call_next(request)
|
| 605 |
+
ctype = response.headers.get("content-type", "")
|
| 606 |
+
if not (index and ctype.startswith("text/html")):
|
| 607 |
+
return response
|
| 608 |
+
body = b"".join([chunk async for chunk in response.body_iterator])
|
| 609 |
+
if b"</head>" in body and b'rel="canonical"' not in body:
|
| 610 |
+
body = body.replace(b"</head>", CANONICAL_HEAD.encode("utf-8") + b"</head>", 1)
|
| 611 |
+
headers = {k: v for k, v in response.headers.items()
|
| 612 |
+
if k.lower() not in ("content-length", "content-encoding")}
|
| 613 |
+
return Response(content=body, status_code=response.status_code,
|
| 614 |
+
headers=headers, media_type="text/html")
|
| 615 |
+
|
| 616 |
+
app = FastAPI()
|
| 617 |
+
app.add_middleware(CanonicalMiddleware)
|
| 618 |
+
gr.mount_gradio_app(app, demo, path="/", ssr_mode=False)
|
| 619 |
+
uvicorn.run(app, host="0.0.0.0", port=port)
|
| 620 |
+
|
| 621 |
+
|
| 622 |
if __name__ == "__main__":
|
| 623 |
+
_serve_with_canonical()
|