File size: 4,269 Bytes
1172c9b
3fedaf6
a73ed13
 
 
 
 
 
b3c589e
a73ed13
b3c589e
 
3fedaf6
a73ed13
 
 
 
 
 
 
3fedaf6
 
 
a73ed13
 
b3c589e
 
 
 
 
 
 
3fedaf6
 
 
 
 
 
a73ed13
 
 
 
 
 
b3c589e
 
 
 
821a3cc
a73ed13
ad308ee
b3c589e
8d97c7a
a73ed13
2bb0333
 
 
 
a73ed13
2bb0333
 
 
a73ed13
2bb0333
 
 
 
 
 
 
 
 
 
 
 
 
 
a73ed13
 
2bb0333
a24ed54
 
 
 
 
2bb0333
a24ed54
 
8d97c7a
 
 
 
a24ed54
8d97c7a
 
a24ed54
2bb0333
a24ed54
2bb0333
 
8d97c7a
a24ed54
8d97c7a
 
 
 
 
 
a24ed54
 
3fedaf6
a24ed54
 
 
b3c589e
 
1172c9b
b3c589e
1172c9b
 
 
 
b3c589e
511f5c8
 
b3c589e
a73ed13
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse
import cv2
import os
import pandas as pd
import numpy as np
from typing import List, Any
from pydantic import BaseModel
from pymongo import MongoClient
import dns.resolver
from pymongo.server_api import ServerApi
from datetime import datetime
import base64
from detect import detect_with_yolo
from tableocr import get_list
from deskew import deskew
from read_data import get_text


os.environ['KMP_DUPLICATE_LIB_OK'] = 'True'

app = FastAPI()

dns.resolver.default_resolver=dns.resolver.Resolver(configure=False)
dns.resolver.default_resolver.nameservers=['8.8.8.8']

uri = "mongodb+srv://senel1806:dEWqI0FVFMDRpiFl@cluster0.f2kg7rn.mongodb.net/?retryWrites=true&w=majority&appName=Cluster0"
client = MongoClient(uri, server_api=ServerApi('1'))
db = client['invoices']
collection = db['invoices']


class ProcessedData(BaseModel):
    company_name: str
    invoice_number: str
    invoice_date: str
    table_data: List[Any]

class ImageData(BaseModel):
    image: str

class BatchProcessedData(BaseModel):
    results: List[ProcessedData]

class Invoice(BaseModel):
    code: str
    timestamp: str
    date: str
    isTransferred: bool
    images: List[Any]
    data: List[Any]

def extractData(input_img):
    result_img, table_img, company_img, number_img, date_img = detect_with_yolo(input_img)
    try:
        company_name = ""  # Şirket adı
        if company_img is not None and company_img.size > 0:
            company_name = get_text(company_img)
    
        invoice_number = ""  # Fatura numarası
        if number_img is not None and number_img.size > 0:
            invoice_number = get_text(number_img)
    
        invoice_date = ""  # Fatura tarihi
        if date_img is not None and date_img.size > 0:
            invoice_date = get_text(date_img)
    
        table_img = deskew(table_img)
        data = get_list(table_img)
        max_columns = max(len(row) for row in data)
        column_names = [f"Column{i+1}" for i in range(max_columns)]  # Column1, Column2, ... şeklinde sütun adları oluştur
        df = pd.DataFrame(data, columns=column_names)
    except:
        df = pd.DataFrame()
        company_name = ""
        invoice_number = ""
        invoice_date = ""
    return df, company_name, invoice_number, invoice_date


@app.post("/process-images/", response_model=ProcessedData)
async def process_image(image_data: ImageData):
    # Ensure the image data is provided
    if not image_data:
        raise HTTPException(status_code=400, detail="Image data cannot be empty.")
    
    try:
        # Decode the base64 image data
        image_bytes = base64.b64decode(image_data.image)
        nparr = np.frombuffer(image_bytes, np.uint8)
        img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        # Extract data from the image using your custom method
        df, company_name, invoice_number, invoice_date = extractData(img)
        
        # If the table data is empty, use an empty list
        if df.empty:
            table_data = []
        else:
            table_data = df.to_dict(orient='records')
        
        # Prepare the response data
        response_data = ProcessedData(
            company_name=company_name,
            invoice_number=invoice_number,
            invoice_date=invoice_date,
            table_data=table_data
        )
        print(response_data)
        return response_data  # Return the processed data as a response
    
    except Exception as e:
        # Handle any errors that occur during processing
        raise HTTPException(status_code=500, detail=f"Error processing the image: {str(e)}")

@app.post("/save-invoice")
async def save_invoice(invoice: Invoice, request: Request):
    try:
        invoice_data = await request.json()
        print("Received payload:", invoice_data)  # Log the payload
        invoice = Invoice(**invoice_data)  # Validate the payload using Pydantic
        collection.insert_one(invoice.model_dump())
        return {"message": "Invoice saved successfully"}
    except ValidationError as e:
        raise HTTPException(status_code=422, detail=e.errors())
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))