Spaces:
				
			
			
	
			
			
					
		Running
		
	
	
	
			
			
	
	
	
	
		
		
					
		Running
		
	Update app.py
Browse files
    	
        app.py
    CHANGED
    
    | @@ -1,95 +1,104 @@ | |
| 1 | 
            -
            # app.py β DeepSeek-OCR (HF Space,  | 
| 2 | 
            -
            #  | 
| 3 | 
            -
            #  | 
| 4 |  | 
| 5 | 
            -
            import io, os, sys, base64, traceback
         | 
| 6 | 
             
            from typing import Optional
         | 
| 7 | 
             
            from PIL import Image
         | 
| 8 | 
             
            import numpy as np
         | 
| 9 | 
             
            import gradio as gr
         | 
| 10 | 
            -
            from fastapi import FastAPI, UploadFile, File, Body
         | 
| 11 | 
            -
            from fastapi.responses import JSONResponse
         | 
| 12 |  | 
| 13 | 
            -
            # βββββββββββββββββββββββββββββββββββββββββββββ
         | 
| 14 | 
            -
            # 1. κ²½λ‘ μλ μΈμ
         | 
| 15 | 
            -
            # βββββββββββββββββββββββββββββββββββββββββββββ
         | 
| 16 | 
             
            ROOT = os.path.dirname(__file__)
         | 
| 17 | 
            -
             | 
|  | |
|  | |
| 18 | 
             
                "DeepSeek-OCR-master",
         | 
| 19 | 
            -
                "DeepSeek-OCR-hf",
         | 
| 20 | 
             
                os.path.join("DeepSeek-OCR-main", "DeepSeek-OCR-master"),
         | 
|  | |
| 21 | 
             
                os.path.join("DeepSeek-OCR-main", "DeepSeek-OCR-hf"),
         | 
| 22 | 
             
            ]
         | 
| 23 | 
            -
            for rel in CANDIDATES:
         | 
| 24 | 
            -
                absdir = os.path.join(ROOT, rel)
         | 
| 25 | 
            -
                if os.path.isdir(absdir) and absdir not in sys.path:
         | 
| 26 | 
            -
                    sys.path.append(absdir)
         | 
| 27 | 
            -
                    print(f"[path] added: {absdir}")
         | 
| 28 |  | 
| 29 | 
            -
             | 
| 30 | 
            -
            #  | 
| 31 | 
            -
            #  | 
| 32 | 
            -
             | 
| 33 | 
            -
             | 
| 34 | 
            -
                    self.fn = None
         | 
| 35 | 
            -
             | 
| 36 | 
            -
                    # (1) deepseek_ocr.py
         | 
| 37 | 
            -
                    try:
         | 
| 38 | 
            -
                        import deepseek_ocr as dso
         | 
| 39 | 
            -
                        if hasattr(dso, "ocr_image"):
         | 
| 40 | 
            -
                            self.fn = lambda img, lang="auto": dso.ocr_image(img, lang=lang)
         | 
| 41 | 
            -
                            print("[Adapter] Using deepseek_ocr.ocr_image()")
         | 
| 42 | 
            -
                            return
         | 
| 43 | 
            -
                        if hasattr(dso, "DeepSeekOCR"):
         | 
| 44 | 
            -
                            model = dso.DeepSeekOCR()
         | 
| 45 | 
            -
                            self.fn = lambda img, lang="auto": model.recognize(img, lang=lang)
         | 
| 46 | 
            -
                            print("[Adapter] Using deepseek_ocr.DeepSeekOCR()")
         | 
| 47 | 
            -
                            return
         | 
| 48 | 
            -
                    except Exception as e:
         | 
| 49 | 
            -
                        print("[Adapter] deepseek_ocr import failed:", e)
         | 
| 50 |  | 
| 51 | 
            -
             | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 52 | 
             
                    try:
         | 
| 53 | 
            -
                         | 
| 54 | 
            -
                         | 
| 55 | 
            -
             | 
| 56 | 
            -
                             | 
|  | |
|  | |
| 57 | 
             
                            return
         | 
| 58 | 
            -
                         | 
| 59 | 
            -
             | 
| 60 | 
            -
                             | 
| 61 | 
            -
                             | 
| 62 | 
            -
             | 
| 63 | 
            -
             | 
| 64 | 
            -
             | 
| 65 | 
            -
             | 
| 66 | 
            -
             | 
| 67 | 
            -
                         | 
| 68 | 
            -
             | 
| 69 | 
            -
             | 
| 70 | 
            -
                                fn = getattr(runner, cand)
         | 
| 71 | 
             
                                def _call(img, lang="auto", _fn=fn):
         | 
| 72 | 
            -
                                     | 
| 73 | 
            -
                                    with tempfile.NamedTemporaryFile(suffix=".png", delete= | 
| 74 | 
             
                                        img.save(tmp.name)
         | 
| 75 | 
            -
                                         | 
| 76 | 
            -
             | 
| 77 | 
            -
             | 
|  | |
|  | |
|  | |
|  | |
|  | |
| 78 | 
             
                                return
         | 
| 79 | 
             
                    except Exception as e:
         | 
| 80 | 
            -
                        print("[Adapter]  | 
|  | |
| 81 |  | 
| 82 | 
             
                    # fallback
         | 
| 83 | 
            -
                    self. | 
| 84 | 
            -
                     | 
| 85 |  | 
| 86 | 
            -
                def recognize(self, image: Image.Image, lang="auto"):
         | 
| 87 | 
            -
                    return self. | 
| 88 |  | 
|  | |
| 89 |  | 
| 90 | 
            -
            # βββββββββββββββββββββββββββββββββββββββββββββ
         | 
| 91 | 
            -
            # 3. μ νΈ
         | 
| 92 | 
            -
            # βββββββββββββββββββββββββββββββββββββββββββββ
         | 
| 93 | 
             
            def _to_pil(x) -> Image.Image:
         | 
| 94 | 
             
                if isinstance(x, Image.Image):
         | 
| 95 | 
             
                    return x.convert("RGB")
         | 
| @@ -100,53 +109,17 @@ def _to_pil(x) -> Image.Image: | |
| 100 | 
             
                raise TypeError("Unsupported image type")
         | 
| 101 |  | 
| 102 | 
             
            def _b64_to_image(image_b64: str) -> Image.Image:
         | 
|  | |
| 103 | 
             
                return _to_pil(base64.b64decode(image_b64))
         | 
| 104 |  | 
| 105 | 
            -
             | 
| 106 | 
            -
             | 
| 107 | 
            -
                 | 
| 108 | 
            -
                r.raise_for_status()
         | 
| 109 | 
            -
                return _to_pil(r.content)
         | 
| 110 | 
            -
             | 
| 111 | 
            -
             | 
| 112 | 
            -
            # βββββββββββββββββββββββββββββββββββββββββββββ
         | 
| 113 | 
            -
            # 4. FastAPI
         | 
| 114 | 
            -
            # βββββββββββββββββββββββββββββββββββββββββββββ
         | 
| 115 | 
            -
            api = FastAPI(title="DeepSeek-OCR API")
         | 
| 116 | 
            -
            _engine = DeepSeekOCRAdapter()
         | 
| 117 | 
            -
             | 
| 118 | 
            -
            @api.post("/ocr")
         | 
| 119 | 
            -
            async def ocr_endpoint(
         | 
| 120 | 
            -
                image_b64: Optional[str] = Body(default=None),
         | 
| 121 | 
            -
                image_url: Optional[str] = Body(default=None),
         | 
| 122 | 
            -
                lang: str = Body(default="auto"),
         | 
| 123 | 
            -
                file: Optional[UploadFile] = File(default=None),
         | 
| 124 | 
            -
            ):
         | 
| 125 | 
            -
                try:
         | 
| 126 | 
            -
                    if file:
         | 
| 127 | 
            -
                        image = _to_pil(await file.read())
         | 
| 128 | 
            -
                    elif image_b64:
         | 
| 129 | 
            -
                        image = _b64_to_image(image_b64)
         | 
| 130 | 
            -
                    elif image_url:
         | 
| 131 | 
            -
                        image = _url_to_image(image_url)
         | 
| 132 | 
            -
                    else:
         | 
| 133 | 
            -
                        return JSONResponse(status_code=400, content={"ok": False, "error": "No image input"})
         | 
| 134 | 
            -
                    text = _engine.recognize(image, lang)
         | 
| 135 | 
            -
                    return {"ok": True, "text": text}
         | 
| 136 | 
            -
                except Exception as e:
         | 
| 137 | 
            -
                    return JSONResponse(status_code=500, content={"ok": False, "error": str(e), "trace": traceback.format_exc()})
         | 
| 138 | 
            -
             | 
| 139 | 
            -
             | 
| 140 | 
            -
            # βββββββββββββββββββββββββββββββββββββββββββββ
         | 
| 141 | 
            -
            # 5. Gradio UI
         | 
| 142 | 
            -
            # βββββββββββββββββββββββββββββββββββββββββββββ
         | 
| 143 | 
            -
            def gradio_predict(img, lang):
         | 
| 144 | 
            -
                if img is None:
         | 
| 145 | 
             
                    return "No image provided."
         | 
| 146 | 
            -
                return  | 
| 147 |  | 
| 148 | 
            -
            with gr.Blocks(title="DeepSeek-OCR ( | 
| 149 | 
            -
                gr.Markdown("### DeepSeek-OCR (HF Space)\n | 
| 150 | 
             
                with gr.Row():
         | 
| 151 | 
             
                    img = gr.Image(type="pil", label="Input Image")
         | 
| 152 | 
             
                    out = gr.Textbox(label="OCR Result", lines=8)
         | 
| @@ -154,5 +127,5 @@ with gr.Blocks(title="DeepSeek-OCR (Claude Ready)") as demo: | |
| 154 | 
             
                btn = gr.Button("Run OCR")
         | 
| 155 | 
             
                btn.click(gradio_predict, inputs=[img, lang], outputs=[out])
         | 
| 156 |  | 
| 157 | 
            -
             | 
| 158 | 
            -
            demo.queue()  #  | 
|  | |
| 1 | 
            +
            # app.py β DeepSeek-OCR (HF Space, Gradio-only stable)
         | 
| 2 | 
            +
            # - Gradio UI μ κ³΅ (Claude Skillμ Gradio /run/predict APIλ‘ νΈμΆ)
         | 
| 3 | 
            +
            # - deepseek_ocr.py λλ run_dpsk_ocr_image.pyλ₯Ό νμΌκ²½λ‘λ‘ μ§μ  λ‘λ
         | 
| 4 |  | 
| 5 | 
            +
            import io, os, sys, base64, importlib.util, tempfile, traceback
         | 
| 6 | 
             
            from typing import Optional
         | 
| 7 | 
             
            from PIL import Image
         | 
| 8 | 
             
            import numpy as np
         | 
| 9 | 
             
            import gradio as gr
         | 
|  | |
|  | |
| 10 |  | 
|  | |
|  | |
|  | |
| 11 | 
             
            ROOT = os.path.dirname(__file__)
         | 
| 12 | 
            +
             | 
| 13 | 
            +
            # ν보 λλ ν°λ¦¬: 루νΈ/DeepSeek-OCR-master, DeepSeek-OCR-main/DeepSeek-OCR-master, DeepSeek-OCR-hf λ±
         | 
| 14 | 
            +
            DIR_CANDIDATES = [
         | 
| 15 | 
             
                "DeepSeek-OCR-master",
         | 
|  | |
| 16 | 
             
                os.path.join("DeepSeek-OCR-main", "DeepSeek-OCR-master"),
         | 
| 17 | 
            +
                "DeepSeek-OCR-hf",
         | 
| 18 | 
             
                os.path.join("DeepSeek-OCR-main", "DeepSeek-OCR-hf"),
         | 
| 19 | 
             
            ]
         | 
|  | |
|  | |
|  | |
|  | |
|  | |
| 20 |  | 
| 21 | 
            +
            FILE_CANDIDATES = [
         | 
| 22 | 
            +
                "deepseek_ocr.py",           # ν¨μν λλ ν΄λμ€ν μνΈλ¦¬ κΈ°λ
         | 
| 23 | 
            +
                "run_dpsk_ocr_image.py",     # CLI μ€νμΌ μνΈλ¦¬ κ°λ₯
         | 
| 24 | 
            +
                "run_dpsk_ocr.py",           # HF μ€ν¬λ¦½νΈ
         | 
| 25 | 
            +
            ]
         | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 26 |  | 
| 27 | 
            +
            def _find_file():
         | 
| 28 | 
            +
                for d in DIR_CANDIDATES:
         | 
| 29 | 
            +
                    absd = os.path.join(ROOT, d)
         | 
| 30 | 
            +
                    if not os.path.isdir(absd):
         | 
| 31 | 
            +
                        continue
         | 
| 32 | 
            +
                    for fname in FILE_CANDIDATES:
         | 
| 33 | 
            +
                        path = os.path.join(absd, fname)
         | 
| 34 | 
            +
                        if os.path.isfile(path):
         | 
| 35 | 
            +
                            return path
         | 
| 36 | 
            +
                return None
         | 
| 37 | 
            +
             | 
| 38 | 
            +
            def _load_module_from_path(path: str):
         | 
| 39 | 
            +
                name = os.path.splitext(os.path.basename(path))[0]
         | 
| 40 | 
            +
                spec = importlib.util.spec_from_file_location(name, path)
         | 
| 41 | 
            +
                if spec is None or spec.loader is None:
         | 
| 42 | 
            +
                    raise ImportError(f"Cannot load module from {path}")
         | 
| 43 | 
            +
                mod = importlib.util.module_from_spec(spec)
         | 
| 44 | 
            +
                sys.modules[name] = mod
         | 
| 45 | 
            +
                spec.loader.exec_module(mod)
         | 
| 46 | 
            +
                return mod
         | 
| 47 | 
            +
             | 
| 48 | 
            +
            class OCRAdapter:
         | 
| 49 | 
            +
                def __init__(self):
         | 
| 50 | 
            +
                    self.entry = None
         | 
| 51 | 
            +
                    self.mode = "demo"
         | 
| 52 | 
            +
                    self.path = _find_file()
         | 
| 53 | 
            +
                    print(f"[Adapter] candidate path: {self.path}")
         | 
| 54 | 
            +
                    if not self.path:
         | 
| 55 | 
            +
                        return
         | 
| 56 | 
             
                    try:
         | 
| 57 | 
            +
                        mod = _load_module_from_path(self.path)
         | 
| 58 | 
            +
                        # 1) ν¨μν μνΈλ¦¬: ocr_image(image, lang="auto")
         | 
| 59 | 
            +
                        if hasattr(mod, "ocr_image"):
         | 
| 60 | 
            +
                            self.entry = lambda img, lang="auto": mod.ocr_image(img, lang=lang)
         | 
| 61 | 
            +
                            self.mode = "func_ocr_image"
         | 
| 62 | 
            +
                            print("[Adapter] using ocr_image(image, lang)")
         | 
| 63 | 
             
                            return
         | 
| 64 | 
            +
                        # 2) ν΄λμ€ν μνΈλ¦¬: DeepSeekOCR().recognize(image, lang)
         | 
| 65 | 
            +
                        if hasattr(mod, "DeepSeekOCR"):
         | 
| 66 | 
            +
                            inst = mod.DeepSeekOCR()
         | 
| 67 | 
            +
                            if hasattr(inst, "recognize"):
         | 
| 68 | 
            +
                                self.entry = lambda img, lang="auto": inst.recognize(img, lang=lang)
         | 
| 69 | 
            +
                                self.mode = "class_recognize"
         | 
| 70 | 
            +
                                print("[Adapter] using DeepSeekOCR().recognize(image, lang)")
         | 
| 71 | 
            +
                                return
         | 
| 72 | 
            +
                        # 3) μ€ν¬λ¦½νΈ/CLIν: run() / infer() / main() β κ²½λ‘ μꡬ κ°λ₯
         | 
| 73 | 
            +
                        for cand in ("run", "infer", "main", "predict"):
         | 
| 74 | 
            +
                            if hasattr(mod, cand):
         | 
| 75 | 
            +
                                fn = getattr(mod, cand)
         | 
|  | |
| 76 | 
             
                                def _call(img, lang="auto", _fn=fn):
         | 
| 77 | 
            +
                                    # μ΄λ―Έμ§κ° νμΌκ²½λ‘λ₯Ό μκ΅¬ν  μ μμΌλ―λ‘ μμ μ μ₯
         | 
| 78 | 
            +
                                    with tempfile.NamedTemporaryFile(suffix=".png", delete=True) as tmp:
         | 
| 79 | 
             
                                        img.save(tmp.name)
         | 
| 80 | 
            +
                                        try:
         | 
| 81 | 
            +
                                            return str(_fn(tmp.name))
         | 
| 82 | 
            +
                                        except TypeError:
         | 
| 83 | 
            +
                                            # νΉμ lang λ± λ€λ₯Έ μΈμ κ΅¬μ‘°μΌ κ²½μ° μλ
         | 
| 84 | 
            +
                                            return str(_fn(tmp.name, lang=lang))
         | 
| 85 | 
            +
                                self.entry = _call
         | 
| 86 | 
            +
                                self.mode = f"script_{cand}"
         | 
| 87 | 
            +
                                print(f"[Adapter] using {os.path.basename(self.path)}.{cand}(...) via temp file")
         | 
| 88 | 
             
                                return
         | 
| 89 | 
             
                    except Exception as e:
         | 
| 90 | 
            +
                        print("[Adapter] load failed:", e)
         | 
| 91 | 
            +
                        print(traceback.format_exc())
         | 
| 92 |  | 
| 93 | 
             
                    # fallback
         | 
| 94 | 
            +
                    self.entry = lambda img, lang="auto": "[DEMO] μ°κ²° μ±κ³΅ β μ€μ  μΆλ‘  ν¨μ νμΈ νμ."
         | 
| 95 | 
            +
                    self.mode = "demo"
         | 
| 96 |  | 
| 97 | 
            +
                def recognize(self, image: Image.Image, lang="auto") -> str:
         | 
| 98 | 
            +
                    return self.entry(image.convert("RGB"), lang)
         | 
| 99 |  | 
| 100 | 
            +
            ADAPTER = OCRAdapter()
         | 
| 101 |  | 
|  | |
|  | |
|  | |
| 102 | 
             
            def _to_pil(x) -> Image.Image:
         | 
| 103 | 
             
                if isinstance(x, Image.Image):
         | 
| 104 | 
             
                    return x.convert("RGB")
         | 
|  | |
| 109 | 
             
                raise TypeError("Unsupported image type")
         | 
| 110 |  | 
| 111 | 
             
            def _b64_to_image(image_b64: str) -> Image.Image:
         | 
| 112 | 
            +
                import base64
         | 
| 113 | 
             
                return _to_pil(base64.b64decode(image_b64))
         | 
| 114 |  | 
| 115 | 
            +
            # ββ Gradio UI (Claude Skillμ /run/predict API μ¬μ©) ββ
         | 
| 116 | 
            +
            def gradio_predict(image, lang):
         | 
| 117 | 
            +
                if image is None:
         | 
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
|  | |
| 118 | 
             
                    return "No image provided."
         | 
| 119 | 
            +
                return ADAPTER.recognize(_to_pil(image), lang)
         | 
| 120 |  | 
| 121 | 
            +
            with gr.Blocks(title="DeepSeek-OCR (HF Gradio)") as demo:
         | 
| 122 | 
            +
                gr.Markdown("### DeepSeek-OCR (HF Space, Gradio)\nνμ¬ λͺ¨λ: **" + ADAPTER.mode + "**  \nκ²½λ‘: " + str(ADAPTER.path))
         | 
| 123 | 
             
                with gr.Row():
         | 
| 124 | 
             
                    img = gr.Image(type="pil", label="Input Image")
         | 
| 125 | 
             
                    out = gr.Textbox(label="OCR Result", lines=8)
         | 
|  | |
| 127 | 
             
                btn = gr.Button("Run OCR")
         | 
| 128 | 
             
                btn.click(gradio_predict, inputs=[img, lang], outputs=[out])
         | 
| 129 |  | 
| 130 | 
            +
            # Hugging Face (sdk: gradio)λ μ μ λ³μ `demo`λ₯Ό μλ μ€νν©λλ€.
         | 
| 131 | 
            +
            # demo.queue()  # νμμ μ¬μ© (λ²μ λ³ μΈμ μμ΄)
         |