alonb19 commited on
Commit
dfff0b8
·
verified ·
1 Parent(s): 0512966

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +68 -68
app.py CHANGED
@@ -1,68 +1,68 @@
1
- from fastapi import FastAPI, UploadFile, File, HTTPException
2
- from fastapi.responses import JSONResponse
3
- import easyocr
4
- import numpy as np
5
- from PIL import Image
6
- import io
7
- import uvicorn
8
- import os
9
-
10
- app = FastAPI()
11
-
12
- # Inicializar el lector OCR
13
- reader = easyocr.Reader(['es', 'en'])
14
-
15
- @app.post("/ocr")
16
- async def extract_text(file: UploadFile = File(...)):
17
- """
18
- Extrae texto de una imagen usando OCR
19
- """
20
- try:
21
- # Verificar que el archivo sea una imagen
22
- if not file.content_type.startswith('image/'):
23
- raise HTTPException(status_code=400, detail="El archivo debe ser una imagen")
24
-
25
- # Leer el archivo
26
- contents = await file.read()
27
-
28
- # Convertir a PIL Image
29
- image = Image.open(io.BytesIO(contents))
30
-
31
- # Convertir a RGB si es necesario
32
- if image.mode != 'RGB':
33
- image = image.convert('RGB')
34
-
35
- # Convertir a numpy array
36
- image_array = np.array(image)
37
-
38
- # Realizar OCR
39
- results = reader.readtext(image_array)
40
-
41
- # Formatear resultados
42
- extracted_text = []
43
- for (bbox, text, confidence) in results:
44
- extracted_text.append({
45
- "text": text,
46
- "confidence": float(confidence),
47
- "bbox": bbox
48
- })
49
-
50
- # Texto completo concatenado
51
- full_text = " ".join([item["text"] for item in extracted_text])
52
-
53
- return JSONResponse(content={
54
- "success": True,
55
- "full_text": full_text,
56
- "detailed_results": extracted_text
57
- })
58
-
59
- except Exception as e:
60
- raise HTTPException(status_code=500, detail=f"Error procesando la imagen: {str(e)}")
61
-
62
- @app.get("/")
63
- async def root():
64
- return {"message": "OCR API funcionando", "endpoint": "/ocr"}
65
-
66
- if __name__ == "__main__":
67
- port = int(os.environ.get("PORT", 7860))
68
- uvicorn.run(app, host="0.0.0.0", port=port)
 
1
+ from fastapi import FastAPI, UploadFile, File, HTTPException
2
+ from fastapi.responses import JSONResponse
3
+ import easyocr
4
+ import numpy as np
5
+ from PIL import Image
6
+ import io
7
+ import uvicorn
8
+ import os
9
+
10
+ app = FastAPI()
11
+
12
+ # Inicializar el lector OCR
13
+ reader = easyocr.Reader(['es', 'en'], model_storage_directory='/app/model', user_network_directory='/app/user_network', recog_network='custom')
14
+
15
+ @app.post("/ocr")
16
+ async def extract_text(file: UploadFile = File(...)):
17
+ """
18
+ Extrae texto de una imagen usando OCR
19
+ """
20
+ try:
21
+ # Verificar que el archivo sea una imagen
22
+ if not file.content_type.startswith('image/'):
23
+ raise HTTPException(status_code=400, detail="El archivo debe ser una imagen")
24
+
25
+ # Leer el archivo
26
+ contents = await file.read()
27
+
28
+ # Convertir a PIL Image
29
+ image = Image.open(io.BytesIO(contents))
30
+
31
+ # Convertir a RGB si es necesario
32
+ if image.mode != 'RGB':
33
+ image = image.convert('RGB')
34
+
35
+ # Convertir a numpy array
36
+ image_array = np.array(image)
37
+
38
+ # Realizar OCR
39
+ results = reader.readtext(image_array)
40
+
41
+ # Formatear resultados
42
+ extracted_text = []
43
+ for (bbox, text, confidence) in results:
44
+ extracted_text.append({
45
+ "text": text,
46
+ "confidence": float(confidence),
47
+ "bbox": bbox
48
+ })
49
+
50
+ # Texto completo concatenado
51
+ full_text = " ".join([item["text"] for item in extracted_text])
52
+
53
+ return JSONResponse(content={
54
+ "success": True,
55
+ "full_text": full_text,
56
+ "detailed_results": extracted_text
57
+ })
58
+
59
+ except Exception as e:
60
+ raise HTTPException(status_code=500, detail=f"Error procesando la imagen: {str(e)}")
61
+
62
+ @app.get("/")
63
+ async def root():
64
+ return {"message": "OCR API funcionando", "endpoint": "/ocr"}
65
+
66
+ if __name__ == "__main__":
67
+ port = int(os.environ.get("PORT", 7860))
68
+ uvicorn.run(app, host="0.0.0.0", port=port)