File size: 8,439 Bytes
a80a32e
 
374083e
a80a32e
374083e
5de371d
 
 
 
a80a32e
374083e
 
 
a80a32e
374083e
a80a32e
 
 
 
 
 
 
 
 
 
 
 
31e30cc
a80a32e
 
 
 
 
374083e
a80a32e
 
 
374083e
a80a32e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
374083e
a80a32e
 
 
 
 
 
 
cf220c1
a80a32e
cf220c1
a80a32e
374083e
a80a32e
 
 
 
 
 
 
 
 
 
 
 
374083e
 
 
 
a80a32e
 
cf220c1
 
 
a80a32e
 
374083e
a80a32e
 
374083e
a80a32e
374083e
 
a80a32e
374083e
 
 
a80a32e
5de371d
 
a80a32e
374083e
 
a80a32e
374083e
 
 
 
 
a80a32e
374083e
 
 
 
a80a32e
 
374083e
 
 
cf220c1
 
374083e
a80a32e
 
 
cf220c1
 
a80a32e
 
 
 
 
374083e
a80a32e
374083e
 
a80a32e
cf220c1
 
374083e
 
 
a80a32e
374083e
 
a80a32e
374083e
5de371d
374083e
a80a32e
5de371d
 
 
 
 
 
 
021b753
a80a32e
cf220c1
021b753
5de371d
374083e
a80a32e
 
374083e
a80a32e
 
cf220c1
374083e
a80a32e
 
374083e
a80a32e
374083e
 
a80a32e
374083e
 
 
a80a32e
374083e
 
a80a32e
374083e
 
 
a80a32e
374083e
 
a80a32e
374083e
a80a32e
374083e
 
a80a32e
 
374083e
 
 
 
 
 
 
 
 
 
a80a32e
 
 
374083e
a80a32e
 
374083e
 
a80a32e
 
374083e
 
a80a32e
 
374083e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
31e30cc
 
374083e
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
"""
audiolens β€” app.py
huggingface space backend (zerogpu + gradio native api)

api endpoints (via gradio):
    /call/classify   β€” document type classification (dit-base)
    /call/ocr        β€” text extraction (easyocr)
    /call/speak      β€” text to speech (kokoro)
    /call/health     β€” check if space is warm

the pwa calls these using the gradio js client (@gradio/client)
or via gradio's rest api. each function decorated with @spaces.GPU
gets a gpu allocation only for the duration of that call.

llm extraction (gemini) is called directly from the pwa β€” not here.
"""

import io
import warnings
warnings.filterwarnings('ignore')

import numpy as np
import cv2
from PIL import Image

import torch
import spaces
import gradio as gr

from j2_preprocess import preprocess


# ============================================================
# -- dit class mapping --
# ============================================================

# dit maps its 16 rvl-cdip classes to audiolens categories
# indices must match the 9 classes we selected in j1
DIT_CLASS_MAP = {
    0:  'letter',
    1:  'form',
    2:  'email',
    3:  'handwritten',
    4:  'advertisement',
    7:  'specification',
    9:  'news_article',
    10: 'budget',
    11: 'invoice',
}
SELECTED_RVL_IDX = list(DIT_CLASS_MAP.keys())


# ============================================================
# -- model loading (runs once at startup, cpu ram) --
# ============================================================

print('loading models...')

# -- classifier: dit-base --
from transformers import AutoImageProcessor, AutoModelForImageClassification

dit_processor = AutoImageProcessor.from_pretrained('microsoft/dit-base-finetuned-rvlcdip')
dit_model     = AutoModelForImageClassification.from_pretrained('microsoft/dit-base-finetuned-rvlcdip')
dit_model.eval()
print('dit-base loaded.')

# -- ocr: easyocr (lazy-init on first call, runs on cpu to save gpu quota) --
ocr_reader = None
print('easyocr will lazy-init on first ocr request (cpu).')

# -- tts: kokoro --
import soundfile as sf
from kokoro import KPipeline
kokoro_pipeline = KPipeline(lang_code='b')   # b = british english
print('kokoro loaded.')

print('all models ready.')


# ============================================================
# -- helpers --
# ============================================================

def pil_to_cv2(pil_image):
    """converts a pil rgb image to a bgr numpy array for opencv."""
    rgb = np.array(pil_image)
    return cv2.cvtColor(rgb, cv2.COLOR_RGB2BGR)


# -- endpoint section: ocr --
# preprocesses the image then runs easyocr β€” both on cpu.
# saves gpu quota for classify and tts only.

@spaces.GPU
def classify_fn(image):
    """
    classifies a document image into one of 9 categories.
    called via gradio api: /call/classify

    input:  pil image (gradio Image component with type="pil")
    output: json dict with doc_type and confidence
    """
    if image is None:
        return {'error': 'no image provided'}

    try:
        dit_model.to('cuda')
        inputs = dit_processor(images=image, return_tensors='pt').to('cuda')

        with torch.no_grad():
            logits = dit_model(**inputs).logits

        # slice to our 9 selected classes and get the winner
        selected_logits = logits[0, SELECTED_RVL_IDX]
        pred_idx        = selected_logits.argmax().item()
        confidence      = torch.softmax(selected_logits, dim=0)[pred_idx].item()
        doc_type        = DIT_CLASS_MAP[SELECTED_RVL_IDX[pred_idx]]

        return {'doc_type': doc_type, 'confidence': round(confidence, 4)}

    except Exception as e:
        return {'error': str(e)}


def ocr_gpu(clean_image):
    """
    runs easyocr on a preprocessed image.
    runs on cpu to save gpu quota β€” easyocr is fast enough on cpu.
    lazy-inits on first call.
    """
    global ocr_reader
    if ocr_reader is None:
        import easyocr
        ocr_reader = easyocr.Reader(['en'], gpu=False, verbose=False)
        print('easyocr initialised on cpu.')

    results = ocr_reader.readtext(clean_image, detail=0)
    return ' '.join(results)


def ocr_fn(image):
    """
    extracts text from a document image.
    called via gradio api: /call/ocr

    both preprocessing and ocr run on cpu to save gpu quota.
    easyocr is fast enough on cpu for document-sized images.

    input:  pil image (gradio Image component with type="pil")
    output: extracted text string
    """
    if image is None:
        return 'error: no image provided'

    try:
        # convert pil to cv2 for preprocessing
        cv2_image = pil_to_cv2(image)

        # # preprocessing runs on cpu β€” outside the gpu function
        # clean = preprocess(cv2_image)

        # # ocr inference on cpu
        # text = ocr_gpu(clean)

        # trusting easyOCR for test preprocess
        # clean = preprocess(cv2_image)

        # ocr inference on cpu
        text = ocr_gpu(cv2_image)

        return text

    except Exception as e:
        return f'error: {str(e)}'


@spaces.GPU(duration=15)
def speak_fn(text, voice):
    """
    converts text to speech using kokoro.
    called via gradio api: /call/speak

    input:  text string + voice id
    output: tuple of (sample_rate, audio_array) for gradio Audio component
    """
    if not text or not text.strip():
        return None

    try:
        if not voice or not voice.strip():
            voice = 'bf_emma'

        chunks = []
        for _, _, audio in kokoro_pipeline(text, voice=voice, speed=1.0):
            chunks.append(audio)

        if not chunks:
            return None

        audio_array = np.concatenate(chunks)

        # gradio Audio expects (sample_rate, numpy_array)
        return (24000, audio_array)

    except Exception as e:
        print(f'tts error: {e}')
        return None


def health_fn():
    """
    simple check to see if the space is warm and models are loaded.
    called via gradio api: /call/health
    """
    return {'status': 'ok', 'models': ['dit-base', 'easyocr', 'kokoro']}


# ============================================================
# -- gradio ui + api --
# ============================================================

with gr.Blocks(title='AudioLens API') as demo:

    gr.Markdown("""
    ## AudioLens API
    **This space provides the AudioLens backend.**
    The AudioLens PWA calls the API endpoints below using the Gradio client.
    """)

    # -- classify tab --
    with gr.Tab('Classify'):
        classify_image = gr.Image(type='pil', label='document image')
        classify_btn   = gr.Button('classify')
        classify_out   = gr.JSON(label='result')
        classify_btn.click(
            fn=classify_fn,
            inputs=classify_image,
            outputs=classify_out,
            api_name='classify',
        )

    # -- ocr tab --
    with gr.Tab('OCR'):
        ocr_image = gr.Image(type='pil', label='document image')
        ocr_btn   = gr.Button('extract text')
        ocr_out   = gr.Textbox(label='extracted text', lines=10)
        ocr_btn.click(
            fn=ocr_fn,
            inputs=ocr_image,
            outputs=ocr_out,
            api_name='ocr',
        )

    # -- speak tab --
    with gr.Tab('Speak'):
        speak_text  = gr.Textbox(label='text to speak', lines=5)
        speak_voice = gr.Textbox(label='voice id', value='bf_emma')
        speak_btn   = gr.Button('generate speech')
        speak_out   = gr.Audio(label='output audio')
        speak_btn.click(
            fn=speak_fn,
            inputs=[speak_text, speak_voice],
            outputs=speak_out,
            api_name='speak',
        )

    # -- health (hidden, api only) --
    health_btn = gr.Button('health', visible=False)
    health_out = gr.JSON(visible=False)
    health_btn.click(
        fn=health_fn,
        inputs=[],
        outputs=health_out,
        api_name='health',
    )

    gr.Markdown("""
    ---
    **API endpoints** (use via [@gradio/client](https://www.gradio.app/guides/getting-started-with-the-js-client)):
    - `/call/classify` β€” document type classification
    - `/call/ocr` β€” text extraction with preprocessing
    - `/call/speak` β€” text to speech
    - `/call/health` β€” check if space is warm

    _This UI is for testing. The AudioLens PWA calls the API directly._
    """)


# launch β€” hf spaces handles this automatically
if __name__ == '__main__':
    demo.launch(server_name='0.0.0.0', server_port=7860)