Spaces:
Sleeping
Sleeping
Update app.py
Browse filesAdd feature to switch between running locally and running in the cloud (cloud is sometimes faster)
app.py
CHANGED
@@ -1,21 +1,42 @@
|
|
|
|
1 |
import gradio as gr
|
2 |
from transformers import pipeline
|
|
|
3 |
|
4 |
-
#
|
5 |
-
|
|
|
|
|
6 |
|
7 |
-
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
return result[0]['generated_text']
|
10 |
|
11 |
# Create the Gradio interface
|
12 |
-
|
13 |
-
|
14 |
-
|
15 |
-
|
16 |
-
|
17 |
-
|
18 |
-
)
|
|
|
|
|
|
|
19 |
|
20 |
-
# Launch the app
|
21 |
iface.launch()
|
|
|
1 |
+
import os
|
2 |
import gradio as gr
|
3 |
from transformers import pipeline
|
4 |
+
from huggingface_hub.inference_api import InferenceApi
|
5 |
|
6 |
+
# Get the token from environment variable
|
7 |
+
hf_token = os.environ.get("HF_TOKEN")
|
8 |
+
if not hf_token:
|
9 |
+
raise ValueError("HF_TOKEN environment variable is not set. Please set it with your Hugging Face API token.")
|
10 |
|
11 |
+
# Initialize both local pipeline and Inference API
|
12 |
+
local_extractor = pipeline("image-to-text", model="microsoft/git-base-textcaps")
|
13 |
+
api_extractor = InferenceApi("microsoft/git-base-textcaps", token=hf_token)
|
14 |
+
|
15 |
+
# Flag to track which mode is active
|
16 |
+
use_api = False
|
17 |
+
|
18 |
+
def switch_mode():
|
19 |
+
global use_api
|
20 |
+
use_api = not use_api
|
21 |
+
return "Using API" if use_api else "Using Local Model"
|
22 |
+
|
23 |
+
def extract_text(image, mode_indicator):
|
24 |
+
if "API" in mode_indicator:
|
25 |
+
result = api_extractor(inputs=image)
|
26 |
+
else:
|
27 |
+
result = local_extractor(image)
|
28 |
return result[0]['generated_text']
|
29 |
|
30 |
# Create the Gradio interface
|
31 |
+
with gr.Blocks() as iface:
|
32 |
+
gr.Markdown("# Image Text Extractor")
|
33 |
+
with gr.Row():
|
34 |
+
image_input = gr.Image(type="pil")
|
35 |
+
text_output = gr.Textbox()
|
36 |
+
mode_button = gr.Button("Switch to API")
|
37 |
+
mode_indicator = gr.Textbox(value="Using Local Model", label="Current Mode")
|
38 |
+
|
39 |
+
mode_button.click(switch_mode, outputs=mode_indicator)
|
40 |
+
image_input.change(extract_text, inputs=[image_input, mode_indicator], outputs=text_output)
|
41 |
|
|
|
42 |
iface.launch()
|