ann-kunshujo / app.py
nakamura196's picture
Update app.py
20cfc19
import gradio as gr
import re
from pathlib import Path
from api import load_annoy_index, analyze_image
annoy_index, mappings = load_annoy_index()
def get_article_text():
article = Path("README.md").read_text()
# Remove the HuggingFace Space app information from the README
article = re.sub(r"^---.+---\s+", "", article, flags=re.MULTILINE + re.DOTALL)
return article
STYLE = """
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" integrity="sha256-YvdLHPgkqJ8DVUxjjnGVlMMJtNimJ6dYkowFFvp4kKs=" crossorigin="anonymous">
"""
def find_matching_images(input_img, n_matches: int = 10):
results = analyze_image(input_img, annoy_index, n_matches=n_matches)
indexes = results[0]
scores = results[1]
images = []
HTML = ""
for i in range(len(indexes)):
index = str(indexes[i])
mapping = mappings[index]
url = mapping["url"]
if url != "":
images.append(url)
score = round((1 - scores[i]) * 100, 1)
HTML += f"""<div class="card mb-3">
<div class="row g-0">
<div class="col-md-4 text-center">
<img style="max-height: 150px" src="{url}" alt="{mapping["name"]}">
</div>
<div class="col-md-8">
<div class="card-body">
<h5 class="card-title">{mapping["name"]}</h5>
<p class="card-text">Rank: {i+1}, Similarity: {score} %</p>
<p class="card-text">
<a target="_blank" href="https://kunshujo2022.dl.itc.u-tokyo.ac.jp/item/{mapping["nconst"]}">View at 「電子展示『捃拾帖』(拡張版)」</a>
</p>
</div>
</div>
</div>
</div>"""
return f"""{STYLE} <div style="height: 600px; overflow-y: auto;">{HTML}</div>"""
iface = gr.Interface(
find_matching_images,
title="類似貼り込み資料検索",
description="""類似する貼り込み資料を検索します。 Upload a picture and find out!
Give it a shot or try one of the sample images below.
Built with great open-source libraries such as PyTorch and Annoy.""",
article=get_article_text(),
inputs=[
gr.inputs.Image(shape=None, label="Your image"),
gr.inputs.Slider(minimum=1, maximum=30, step=1, default=10, label="Number of matches"),
],
# outputs=gr.Gallery(label="類似する貼り込み資料").style(height="100px"),
outputs=gr.HTML(label="類似する貼り込み資料"),
examples=[
["images/025_0085.jpg", 10],
["images/046_0051.jpg", 10],
],
)
iface.launch()