File size: 5,864 Bytes
3dc42e0
3dea398
 
 
 
 
3dc42e0
 
 
3dea398
 
 
 
3dc42e0
 
 
de57d30
 
3dc42e0
3dea398
 
 
 
 
 
 
 
 
 
 
 
 
 
3dc42e0
3dea398
 
 
 
 
 
 
 
3dc42e0
 
 
3dea398
 
3dc42e0
3dea398
 
3dc42e0
3dea398
 
 
 
3dc42e0
3dea398
 
3dc42e0
3dea398
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3dc42e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3dea398
 
 
 
 
 
 
 
 
3dc42e0
3dea398
3dc42e0
 
3dea398
 
3dc42e0
3dea398
 
3dc42e0
3dea398
 
 
 
3dc42e0
 
3dea398
3dc42e0
3dea398
 
 
 
 
 
 
 
 
 
 
 
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
import os
import asyncio
import tempfile
from pathlib import Path
from flask import Flask, request, jsonify, render_template_string
from werkzeug.utils import secure_filename
import torch
from PIL import Image
from transformers import Qwen2_5_VLForConditionalGeneration, AutoProcessor

app = Flask(__name__)
app.config['MAX_CONTENT_LENGTH'] = 16 * 1024 * 1024

DEVICE = torch.device("cuda:0" if torch.cuda.is_available() else "cpu")

# Load model
processor = AutoProcessor.from_pretrained("nanonets/Nanonets-OCR-s", trust_remote_code=True)
model = Qwen2_5_VLForConditionalGeneration.from_pretrained("nanonets/Nanonets-OCR-s", trust_remote_code=True, torch_dtype=torch.float16).to(DEVICE).eval()

HTML_TEMPLATE = '''
<!DOCTYPE html>
<html>
<head>
    <title>OCR Japanese Text</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 600px; margin: 50px auto; padding: 20px; }
        .upload-area { border: 2px dashed #ccc; border-radius: 10px; padding: 40px; text-align: center; margin: 20px 0; }
        .upload-area:hover { border-color: #999; }
        input[type="file"] { margin: 20px 0; }
        button { background: #007bff; color: white; padding: 10px 20px; border: none; border-radius: 5px; cursor: pointer; }
        button:hover { background: #0056b3; }
        .result { margin-top: 20px; padding: 15px; background: #f8f9fa; border-radius: 5px; white-space: pre-wrap; }
        .loading { display: none; color: #666; }
        textarea { width: 100%; padding: 10px; border: 1px solid #ccc; border-radius: 5px; }
    </style>
</head>
<body>
    <h1>OCR Japanese Text Extractor</h1>
    <form id="uploadForm" enctype="multipart/form-data">
        <div class="upload-area">
            <p>Select JPG or PNG image</p>
            <input type="file" id="imageFile" name="image" accept=".jpg,.jpeg,.png" required>
            <br>
            <textarea id="promptText" name="prompt" placeholder="perform OCR from this image and reply me with japanese text only, no comment only one option." rows="3"></textarea>
            <br><button type="submit">Extract Text</button>
        </div>
    </form>
    <div class="loading" id="loading">Processing... Please wait</div>
    <div class="result" id="result"></div>
    <script>
        document.getElementById('promptText').value = 'perform OCR from this image and reply me with japanese text only, no comment only one option.';
        document.getElementById('uploadForm').addEventListener('submit', async (e) => {
            e.preventDefault();
            const formData = new FormData();
            const fileInput = document.getElementById('imageFile');
            const promptInput = document.getElementById('promptText');
            if (!fileInput.files[0]) return;
            formData.append('image', fileInput.files[0]);
            formData.append('prompt', promptInput.value);
            document.getElementById('loading').style.display = 'block';
            document.getElementById('result').innerHTML = '';
            try {
                const response = await fetch('/upload', { method: 'POST', body: formData });
                const data = await response.json();
                document.getElementById('result').innerHTML = data.success ? data.text : 'Error: ' + data.error;
            } catch (error) {
                document.getElementById('result').innerHTML = 'Error: ' + error.message;
            }
            document.getElementById('loading').style.display = 'none';
        });
    </script>
</body>
</html>
'''

def perform_ocr(image_path, prompt):
    try:
        image = Image.open(image_path).convert("RGB")
        messages = [{"role": "user", "content": [{"type": "image"}, {"type": "text", "text": prompt}]}]
        text_prompt = processor.apply_chat_template(messages, add_generation_prompt=True)
        inputs = processor(text=text_prompt, images=[image], return_tensors="pt").to(DEVICE)
        
        with torch.no_grad():
            output = model.generate(**inputs, max_new_tokens=1024, temperature=0.7, do_sample=True)
        
        generated_text = processor.decode(output[0], skip_special_tokens=True)
        # Extract only the generated part (after the prompt)
        if "assistant\n" in generated_text:
            result = generated_text.split("assistant\n")[-1].strip()
        else:
            result = generated_text.strip()
        
        return result
    except Exception as e:
        raise e

@app.route('/')
def index():
    return render_template_string(HTML_TEMPLATE)

@app.route('/upload', methods=['POST'])
def upload_file():
    if 'image' not in request.files:
        return jsonify({'success': False, 'error': 'No image file provided'})
    
    file = request.files['image']
    prompt = request.form.get('prompt', 'perform OCR from this image and reply me with japanese text only, no comment only one option.')
    
    if file.filename == '':
        return jsonify({'success': False, 'error': 'No file selected'})
    
    if not file.filename.lower().endswith(('.jpg', '.jpeg', '.png')):
        return jsonify({'success': False, 'error': 'Only JPG and PNG files allowed'})
    
    try:
        with tempfile.NamedTemporaryFile(delete=False, suffix=Path(file.filename).suffix) as tmp_file:
            file.save(tmp_file.name)
            tmp_path = tmp_file.name
        
        result = perform_ocr(tmp_path, prompt)
        os.unlink(tmp_path)
        
        if result:
            return jsonify({'success': True, 'text': result})
        else:
            return jsonify({'success': False, 'error': 'No text detected'})
    except Exception as e:
        if 'tmp_path' in locals():
            try: os.unlink(tmp_path)
            except: pass
        return jsonify({'success': False, 'error': str(e)})

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=7860)