Update app.py
Browse files
app.py
CHANGED
|
@@ -1,57 +1,171 @@
|
|
| 1 |
-
|
| 2 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
|
| 4 |
-
|
|
|
|
| 5 |
|
| 6 |
-
|
| 7 |
-
USER = "kliU0JlomQ"
|
| 8 |
-
PASS = "vXre5KnfxF"
|
| 9 |
-
USER_AGENT = "IPTVSmarters/1.0.3 (iPad; iOS 13.4.1; Scale/2.00)"
|
| 10 |
|
| 11 |
-
|
| 12 |
-
|
|
|
|
|
|
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 17 |
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 21 |
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
if any(x in path for x in ["player_api.php", "xmltv.php", "get.php"]):
|
| 25 |
-
query_params['username'] = USER
|
| 26 |
-
query_params['password'] = PASS
|
| 27 |
|
| 28 |
-
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
|
| 31 |
try:
|
| 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 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import torch
|
| 3 |
+
import gradio as gr
|
| 4 |
+
import fitz
|
| 5 |
+
from PIL import Image
|
| 6 |
+
import logging
|
| 7 |
|
| 8 |
+
logging.basicConfig(level=logging.INFO)
|
| 9 |
+
logger = logging.getLogger(__name__)
|
| 10 |
|
| 11 |
+
os.environ["TRANSFORMERS_NO_TORCHVISION"] = "1"
|
|
|
|
|
|
|
|
|
|
| 12 |
|
| 13 |
+
_model = None
|
| 14 |
+
_tokenizer = None
|
| 15 |
+
_img_proc = None
|
| 16 |
+
_model_loaded = False
|
| 17 |
|
| 18 |
+
def load_model():
|
| 19 |
+
global _model, _tokenizer, _img_proc, _model_loaded
|
| 20 |
+
|
| 21 |
+
if _model_loaded:
|
| 22 |
+
return
|
| 23 |
+
|
| 24 |
+
try:
|
| 25 |
+
from transformers import Qwen2VLForConditionalGeneration, AutoTokenizer, Qwen2VLImageProcessor
|
| 26 |
+
from peft import PeftModel
|
| 27 |
+
|
| 28 |
+
logger.info("Loading base model...")
|
| 29 |
+
_tokenizer = AutoTokenizer.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", trust_remote_code=True)
|
| 30 |
+
_img_proc = Qwen2VLImageProcessor.from_pretrained("Qwen/Qwen2-VL-2B-Instruct", trust_remote_code=True)
|
| 31 |
+
|
| 32 |
+
base = Qwen2VLForConditionalGeneration.from_pretrained(
|
| 33 |
+
"Qwen/Qwen2-VL-2B-Instruct",
|
| 34 |
+
torch_dtype=torch.float16 if torch.cuda.is_available() else torch.float32,
|
| 35 |
+
device_map="auto" if torch.cuda.is_available() else "cpu"
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
logger.info("Loading LoRA adapter...")
|
| 39 |
+
peft_model = PeftModel.from_pretrained(base, "NaserNajeh/Horoof")
|
| 40 |
+
_model = peft_model.merge_and_unload()
|
| 41 |
+
_model.eval()
|
| 42 |
+
_model_loaded = True
|
| 43 |
+
logger.info("โ
Model loaded!")
|
| 44 |
+
|
| 45 |
+
except Exception as e:
|
| 46 |
+
logger.error(f"Error loading model: {e}")
|
| 47 |
+
raise
|
| 48 |
|
| 49 |
+
def pdf_to_images(pdf_bytes, dpi=220, max_pages=2):
|
| 50 |
+
pages_imgs = []
|
| 51 |
+
doc = fitz.open(stream=pdf_bytes, filetype="pdf")
|
| 52 |
+
|
| 53 |
+
n_pages = min(max_pages, doc.page_count)
|
| 54 |
+
|
| 55 |
+
for i in range(n_pages):
|
| 56 |
+
try:
|
| 57 |
+
page = doc.load_page(i)
|
| 58 |
+
mat = fitz.Matrix(dpi/72, dpi/72)
|
| 59 |
+
pix = page.get_pixmap(matrix=mat, alpha=False)
|
| 60 |
+
|
| 61 |
+
img = Image.frombytes("RGB", [pix.width, pix.height], pix.samples)
|
| 62 |
+
|
| 63 |
+
if max(img.size) > 2048:
|
| 64 |
+
img.thumbnail((2048, 2048), Image.Resampling.LANCZOS)
|
| 65 |
+
|
| 66 |
+
pages_imgs.append((i + 1, img))
|
| 67 |
+
logger.info(f"โ
Converted page {i+1}")
|
| 68 |
+
|
| 69 |
+
except Exception as e:
|
| 70 |
+
logger.error(f"Error on page {i+1}: {e}")
|
| 71 |
+
continue
|
| 72 |
|
| 73 |
+
doc.close()
|
| 74 |
+
return pages_imgs
|
|
|
|
|
|
|
|
|
|
| 75 |
|
| 76 |
+
def ocr_page(pil_img, max_tokens=1200):
|
| 77 |
+
try:
|
| 78 |
+
load_model()
|
| 79 |
+
|
| 80 |
+
messages = [
|
| 81 |
+
{
|
| 82 |
+
"role": "user",
|
| 83 |
+
"content": [
|
| 84 |
+
{"type": "image", "image": pil_img},
|
| 85 |
+
{"type": "text", "text": "ุงูุฑุฃ ุงููุต ุงูุนุฑุจู ูู ุงูุตูุฑุฉ ูู
ุง ูู ุฏูู ุฃู ุชุนุฏูู."},
|
| 86 |
+
],
|
| 87 |
+
}
|
| 88 |
+
]
|
| 89 |
+
|
| 90 |
+
tok = _tokenizer.apply_chat_template(messages, add_generation_prompt=True, tokenize=True, return_tensors="pt")
|
| 91 |
+
vis = _img_proc(images=[pil_img], return_tensors="pt")
|
| 92 |
+
|
| 93 |
+
inputs = {"input_ids": tok}
|
| 94 |
+
inputs.update(vis)
|
| 95 |
+
|
| 96 |
+
if torch.cuda.is_available():
|
| 97 |
+
for k, v in inputs.items():
|
| 98 |
+
if hasattr(v, "to"):
|
| 99 |
+
inputs[k] = v.to("cuda")
|
| 100 |
+
|
| 101 |
+
with torch.inference_mode():
|
| 102 |
+
output_ids = _model.generate(**inputs, max_new_tokens=max_tokens, do_sample=False)
|
| 103 |
+
|
| 104 |
+
generated_part = output_ids[0][len(inputs["input_ids"][0]):]
|
| 105 |
+
result = _tokenizer.decode(generated_part, skip_special_tokens=True).strip()
|
| 106 |
+
|
| 107 |
+
return result if result else "No text extracted"
|
| 108 |
+
|
| 109 |
+
except Exception as e:
|
| 110 |
+
logger.error(f"OCR Error: {e}")
|
| 111 |
+
return f"Error: {e}"
|
| 112 |
+
|
| 113 |
+
def process_pdf(pdf_file, dpi, pages):
|
| 114 |
+
if pdf_file is None:
|
| 115 |
+
return "โ No PDF uploaded"
|
| 116 |
|
| 117 |
try:
|
| 118 |
+
logger.info("๐ Processing PDF...")
|
| 119 |
+
|
| 120 |
+
if hasattr(pdf_file, 'read'):
|
| 121 |
+
pdf_bytes = pdf_file.read()
|
| 122 |
+
else:
|
| 123 |
+
pdf_bytes = pdf_file
|
| 124 |
+
|
| 125 |
+
if not pdf_bytes:
|
| 126 |
+
return "โ Empty file"
|
| 127 |
+
|
| 128 |
+
dpi_val = max(150, min(300, int(dpi)))
|
| 129 |
+
pages_limit = max(1, int(pages))
|
| 130 |
+
|
| 131 |
+
logger.info(f"Converting {pages_limit} pages at {dpi_val} DPI...")
|
| 132 |
+
pages_imgs = pdf_to_images(pdf_bytes, dpi=dpi_val, max_pages=pages_limit)
|
| 133 |
+
|
| 134 |
+
if not pages_imgs:
|
| 135 |
+
return "โ No valid pages"
|
| 136 |
+
|
| 137 |
+
results = []
|
| 138 |
+
for page_num, img in pages_imgs:
|
| 139 |
+
logger.info(f"Processing page {page_num}...")
|
| 140 |
+
text = ocr_page(img)
|
| 141 |
+
results.append(f"๐ **Page {page_num}**\n{'='*60}\n{text}")
|
| 142 |
+
|
| 143 |
+
return "\n\n".join(results)
|
| 144 |
+
|
| 145 |
+
except Exception as e:
|
| 146 |
+
logger.error(f"Error: {e}")
|
| 147 |
+
return f"โ Error: {e}"
|
| 148 |
+
|
| 149 |
+
# Gradio Interface
|
| 150 |
+
with gr.Blocks(title="Horoof OCR") as demo:
|
| 151 |
+
gr.Markdown("""
|
| 152 |
+
# ๐ค Horoof OCR - Arabic Text Extraction
|
| 153 |
+
|
| 154 |
+
**Model**: Qwen2-VL-2B + Horoof LoRA
|
| 155 |
+
**For**: Quran & Arabic Text with Diacritics
|
| 156 |
+
""")
|
| 157 |
+
|
| 158 |
+
with gr.Row():
|
| 159 |
+
with gr.Column(scale=1):
|
| 160 |
+
pdf_input = gr.File(label="๐ Upload PDF", file_types=[".pdf"], type="binary")
|
| 161 |
+
dpi_slider = gr.Slider(150, 300, 220, step=10, label="๐ฏ DPI")
|
| 162 |
+
pages_slider = gr.Slider(1, 10, 2, step=1, label="๐ Pages")
|
| 163 |
+
btn = gr.Button("๐ Extract Text", variant="primary", size="lg")
|
| 164 |
+
|
| 165 |
+
with gr.Column(scale=2):
|
| 166 |
+
output = gr.Textbox(label="๐ Extracted Text", lines=20, show_copy_button=True)
|
| 167 |
+
|
| 168 |
+
btn.click(fn=process_pdf, inputs=[pdf_input, dpi_slider, pages_slider], outputs=output)
|
| 169 |
+
|
| 170 |
+
demo.queue()
|
| 171 |
+
demo.launch()
|