File size: 7,935 Bytes
8700a34
574f9e3
6bbd3ca
bda7361
c39e604
 
af17670
 
e36dd54
70678a5
b3ae078
4556b98
1fab2aa
76bbd8a
836458e
86a0b7a
6bbd3ca
bda7361
 
 
 
 
 
 
 
 
 
0f0bcd2
6fcf927
539adb3
686167b
a90d0cf
c14f4d2
574f9e3
 
 
bda7361
574f9e3
 
 
 
 
6bbd3ca
574f9e3
6bbd3ca
574f9e3
 
6bbd3ca
 
 
 
a82199b
6bbd3ca
 
c39e604
 
 
bda7361
574f9e3
 
 
bda7361
 
574f9e3
420d3c9
bda7361
 
41d335c
574f9e3
 
41d335c
574f9e3
f198fb3
574f9e3
f8ec4b3
574f9e3
 
0ddbc70
 
574f9e3
 
 
 
 
 
 
0ddbc70
 
 
 
f660b8b
0ddbc70
 
 
 
 
1106695
0ddbc70
 
 
 
 
574f9e3
0ddbc70
 
 
574f9e3
0ddbc70
3302f65
539adb3
 
 
 
 
 
 
 
 
 
 
20f087e
539adb3
26decc6
539adb3
 
 
42a6b89
 
 
 
 
 
 
 
 
 
 
d167323
a90d0cf
 
 
 
0a12a49
11d5e31
 
 
0a12a49
 
 
11d5e31
 
 
0a12a49
 
 
11d5e31
0a12a49
 
a90d0cf
 
42a6b89
1fd89c5
 
cfd8768
1fd89c5
cfd8768
 
70678a5
cfd8768
70678a5
 
f4c0f67
 
 
58b3b85
 
1fab2aa
 
 
70678a5
1fab2aa
 
 
e6db199
 
b3ae078
1fd89c5
e6db199
cfd8768
 
1fd89c5
 
70678a5
1fd89c5
 
 
 
 
 
 
cfd8768
1fd89c5
 
cfd8768
1fd89c5
cfd8768
 
1fd89c5
cfd8768
 
 
1fd89c5
cfd8768
36dea63
 
 
 
 
 
 
 
 
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import fitz
from fastapi import FastAPI, File, UploadFile, Form
from fastapi.responses import JSONResponse
from transformers import pipeline
from PIL import Image
from io import BytesIO
from starlette.middleware import Middleware
from starlette.middleware.cors import CORSMiddleware
from pdf2image import convert_from_bytes
from pydub import AudioSegment
import numpy as np
import json
import torchaudio
import torch

app = FastAPI()

# Set up CORS middleware
origins = ["*"]  # or specify your list of allowed origins
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

nlp_qa = pipeline("document-question-answering", model="jinhybr/OCR-DocVQA-Donut")
nlp_qa_v2 = pipeline("document-question-answering", model="faisalraza/layoutlm-invoices")
nlp_qa_v3 = pipeline("question-answering", model="deepset/roberta-base-squad2")
nlp_classification = pipeline("text-classification", model="distilbert/distilbert-base-uncased-finetuned-sst-2-english")
nlp_classification_v2 = pipeline("text-classification", model="cardiffnlp/twitter-roberta-base-sentiment-latest")
nlp_speech_to_text = pipeline("automatic-speech-recognition", model="facebook/wav2vec2-base-960h")

description = """
## Image-based Document QA
This API performs document question answering using a LayoutLMv2-based model.

### Endpoints:
- **POST /uploadfile/:** Upload an image file to extract text and answer provided questions.
- **POST /pdfQA/:** Provide a PDF file to extract text and answer provided questions.
"""

app = FastAPI(docs_url="/", description=description)

@app.post("/uploadfile/", description="Upload an image file to extract text and answer provided questions.")
async def perform_document_qa(
    file: UploadFile = File(...),
    questions: str = Form(...),
):
    try:
        # Read the uploaded file as bytes
        contents = await file.read()

        # Open the image using PIL
        image = Image.open(BytesIO(contents))

        # Perform document question answering for each question using LayoutLMv2-based model
        answers_dict = {}
        for question in questions.split(','):
            result = nlp_qa(
                image,
                question.strip()
            )

            # Access the 'answer' key from the first item in the result list
            answer = result[0]['answer']

            # Format the question as a string without extra characters
            formatted_question = question.strip("[]")

            answers_dict[formatted_question] = answer

        return answers_dict
    except Exception as e:
        return JSONResponse(content=f"Error processing file: {str(e)}", status_code=500)

@app.post("/uploadfilev2/", description="Upload an image file to extract text and answer provided questions.")
async def perform_document_qa(
    file: UploadFile = File(...),
    questions: str = Form(...),
):
    try:
        # Read the uploaded file as bytes
        contents = await file.read()

        # Open the image using PIL
        image = Image.open(BytesIO(contents))

        # Perform document question answering for each question using LayoutLMv2-based model
        answers_dict = {}
        for question in questions.split(','):
            result = nlp_qa_v2(
                image,
                question.strip()
            )

            # Access the 'answer' key from the first item in the result list
            answer = result[0]['answer']

            # Format the question as a string without extra characters
            formatted_question = question.strip("[]")

            answers_dict[formatted_question] = answer

        return answers_dict
    except Exception as e:
        return JSONResponse(content=f"Error processing file: {str(e)}", status_code=500)

@app.post("/uploadfilev3/", description="Upload an image file to extract text and answer provided questions.")
async def perform_document_qa(
    context: str = Form(...),
    question: str = Form(...),
):
    try:
        QA_input = {
            'question': question,
            'context': context
        }
        
        res = nlp_qa_v3(QA_input)

        return res['answer']
    except Exception as e:
        return JSONResponse(content=f"Error processing file: {str(e)}", status_code=500)

@app.post("/classify/", description="Classify the provided text.")
async def classify_text(text: str = Form(...)):
    try:
        # Perform text classification using the pipeline
        result = nlp_classification(text)

        # Return the classification result
        return result
    except Exception as e:
        return JSONResponse(content=f"Error classifying text: {str(e)}", status_code=500)

@app.post("/test_classify/", description="Classify the provided text with positive, neutral, or negative sentiment.")
async def test_classify_text(text: str = Form(...)):
    try:
        # Perform text classification using the updated model that returns positive, neutral, or negative
        result = nlp_classification_v2(text)

        # Print the raw label for debugging purposes (can be removed later)
        raw_label = result[0]['label']
        print(f"Raw label from model: {raw_label}")

        # Map the model labels to human-readable format
        label_map = {
            "negative": "Negative",  
            "neutral": "Neutral",   
            "positive": "Positive"   
        }

        # Get the readable label from the map
        formatted_label = label_map.get(raw_label, "Unknown")

        return {"label": formatted_label, "score": result[0]['score']}
    except Exception as e:
        return JSONResponse(content=f"Error classifying text: {str(e)}", status_code=500)

@app.post("/transcribe_and_answer/", description="Transcribe audio and answer provided questions based on the transcription.")
async def transcribe_and_answer(
    file: UploadFile = File(...),
    questions: str = Form(...)
):
    try:
        # Step 1: Read and convert the audio file
        contents = await file.read()
        audio = AudioSegment.from_file(BytesIO(contents))

        # Step 2: Ensure the audio is mono and resample if needed
        audio = audio.set_channels(1)  # Convert to mono if it's not already
        audio = audio.set_frame_rate(16000)  # Resample to 16000 Hz, commonly required by ASR models

        # Step 3: Export to WAV format and load with torchaudio
        wav_buffer = BytesIO()
        audio.export(wav_buffer, format="wav")
        wav_buffer.seek(0)

        # Load audio using torchaudio
        waveform, sample_rate = torchaudio.load(wav_buffer)
        
        # Convert waveform to float32 and ensure it's a numpy array
        waveform_np = waveform.numpy().astype(np.float32)

        # Step 4: Transcribe the audio
        transcription_result = nlp_speech_to_text(waveform_np)
        transcription_text = transcription_result['text']

        # Step 5: Parse the JSON-formatted questions
        questions_dict = json.loads(questions)

        # Step 6: Answer each question using the transcribed text
        answers_dict = {}
        for key, question in questions_dict.items():
            QA_input = {
                'question': question,
                'context': transcription_text
            }
            
            result = nlp_qa_v3(QA_input)
            answers_dict[key] = result['answer']

        # Step 7: Return transcription + answers
        return {
            "transcription": transcription_text,
            "answers": answers_dict
        }

    except Exception as e:
        return JSONResponse(content={"error": f"Error processing audio or answering questions: {str(e)}"}, status_code=500)

# Set up CORS middleware
origins = ["*"]  # or specify your list of allowed origins
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)