upload-ocr / app.py
CieLZ's picture
Update app.py
de57d30 verified
Raw History Blame Contribute Delete
5.86 kB
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)