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 = '''
OCR Japanese Text
OCR Japanese Text Extractor
Processing... Please wait
'''
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)