|
| 1 | +import os |
| 2 | +from fastapi import APIRouter, UploadFile, File, Form |
| 3 | +from pdf2image import convert_from_path |
| 4 | +from google.cloud import vision |
| 5 | +from typing import List |
| 6 | +import boto3 |
| 7 | +from botocore.exceptions import NoCredentialsError |
| 8 | +from io import BytesIO |
| 9 | +import tempfile |
| 10 | +from openvino.inference_engine import IECore |
| 11 | + |
| 12 | +# Set up your S3 credentials and bucket name |
| 13 | +s3_access_key = "YOUR_S3_ACCESS_KEY" |
| 14 | +s3_secret_access_key = "YOUR_S3_SECRET_ACCESS_KEY" |
| 15 | +s3_bucket_name = "YOUR_S3_BUCKET_NAME" |
| 16 | + |
| 17 | +s3 = boto3.client( |
| 18 | + "s3", |
| 19 | + aws_access_key_id=s3_access_key, |
| 20 | + aws_secret_access_key=s3_secret_access_key |
| 21 | +) |
| 22 | + |
| 23 | +ie = IECore() |
| 24 | + |
| 25 | +# Create an instance of APIRouter |
| 26 | +router = APIRouter() |
| 27 | + |
| 28 | +# Define your OpenVINO model paths |
| 29 | +model_xml = "PATH_TO_MODEL_XML" |
| 30 | +model_bin = "PATH_TO_MODEL_BIN" |
| 31 | + |
| 32 | +# Load the OpenVINO model |
| 33 | +net = ie.read_network(model=model_xml, weights=model_bin) |
| 34 | +exec_net = ie.load_network(network=net, device_name="CPU") |
| 35 | + |
| 36 | +# Define the input and output layer names of your model |
| 37 | +input_layer_name = "YOUR_INPUT_LAYER_NAME" |
| 38 | +output_layer_name = "YOUR_OUTPUT_LAYER_NAME" |
| 39 | + |
| 40 | +# Define any other necessary configuration or parameters |
| 41 | + |
| 42 | +# Rest of the code remains the same... |
| 43 | +# ... |
| 44 | + |
| 45 | +@router.post("/filestotext2") |
| 46 | +async def NotesToText_handler(user: str = Form(...)): |
| 47 | + user = user + "/" |
| 48 | + prefix = 'notes_pdf/' |
| 49 | + prefix2 = 'pyqs_pdf/' |
| 50 | + |
| 51 | + # Delete existing files in the output folders |
| 52 | + delete_folder_objects(user+'images/Notes_images/') |
| 53 | + delete_folder_objects(user+'notes_txt/') |
| 54 | + |
| 55 | + convert(prefix, user) |
| 56 | + convert(prefix2, user) |
| 57 | + |
| 58 | + return {"process completed"} |
| 59 | + |
| 60 | + |
| 61 | +def convert(prefix, user): |
| 62 | + # List files in the S3 bucket with the specified prefix |
| 63 | + response = s3.list_objects_v2(Bucket=s3_bucket_name, Prefix=user+prefix) |
| 64 | + |
| 65 | + # Extract the file names from the response |
| 66 | + files = [obj['Key'] for obj in response.get('Contents', [])] |
| 67 | + |
| 68 | + # Process each file |
| 69 | + for file_name in files: |
| 70 | + file_name = os.path.splitext(os.path.basename(file_name))[0] |
| 71 | + |
| 72 | + print(f"Converting {file_name}....") |
| 73 | + |
| 74 | + # Delete existing files in the output folder |
| 75 | + output_folder = f'{user}images/Notes_images/{file_name}' |
| 76 | + delete_folder_objects(output_folder) |
| 77 | + |
| 78 | + # Download the PDF file from S3 |
| 79 | + pdf_object = s3.get_object(Bucket=s3_bucket_name, Key=f'{user}{prefix}{file_name}.pdf') |
| 80 | + pdf_content = pdf_object['Body'].read() |
| 81 | + |
| 82 | + # Convert the PDF to images and save them in the output folder in S3 |
| 83 | + image_paths, noImg = pdf_to_images_from_bytes(pdf_content, output_folder, file_name) |
| 84 | + print(noImg) |
| 85 | + |
| 86 | + os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = 'Files/client_file_vision.json' |
| 87 | + client = vision.ImageAnnotatorClient() |
| 88 | + |
| 89 | + # [START vision_python_migration_text_detection] |
| 90 | + image_contents = " " |
| 91 | + |
| 92 | + for j in range(noImg): |
| 93 | + image_path = f'{output_folder}/page_{j+1}.jpeg' |
| 94 | + |
| 95 | + # Download the image from S3 |
| 96 | + image_object = s3.get_object(Bucket=s3_bucket_name, Key=image_path) |
| 97 | + image_content = image_object['Body'].read() |
| 98 | + |
| 99 | + image_contents += image_content |
| 100 | + |
| 101 | + # Perform text detection using Google Cloud Vision API |
| 102 | + response = client.text_detection(image=vision.Image(content=image_contents)) |
| 103 | + texts = response.text_annotations |
| 104 | + |
| 105 | + # Extract the detected text |
| 106 | + detected_text = "" |
| 107 | + for text in texts: |
| 108 | + detected_text += text.description |
| 109 | + |
| 110 | + # Save the detected text in a text file |
| 111 | + text_file_path = f'{user}notes_txt/{file_name}.txt' |
| 112 | + upload_text_to_s3(detected_text, text_file_path) |
| 113 | + |
| 114 | + print(f"{file_name} converted.") |
| 115 | + |
| 116 | + |
| 117 | +def pdf_to_images_from_bytes(pdf_bytes, output_folder, file_name): |
| 118 | + images = convert_from_bytes(pdf_bytes) |
| 119 | + image_paths = [] |
| 120 | + noImg = 0 |
| 121 | + |
| 122 | + # Create the output folder if it doesn't exist |
| 123 | + os.makedirs(output_folder, exist_ok=True) |
| 124 | + |
| 125 | + # Save each image as JPEG in the output folder |
| 126 | + for i, image in enumerate(images): |
| 127 | + image_path = f'{output_folder}/page_{i+1}.jpeg' |
| 128 | + image.save(image_path, 'JPEG') |
| 129 | + image_paths.append(image_path) |
| 130 | + noImg += 1 |
| 131 | + |
| 132 | + # Upload images to S3 |
| 133 | + upload_images_to_s3(image_paths, file_name) |
| 134 | + |
| 135 | + return image_paths, noImg |
| 136 | + |
| 137 | + |
| 138 | +def upload_images_to_s3(image_paths, file_name): |
| 139 | + for image_path in image_paths: |
| 140 | + with open(image_path, 'rb') as file: |
| 141 | + try: |
| 142 | + s3.upload_fileobj(file, s3_bucket_name, image_path) |
| 143 | + except NoCredentialsError: |
| 144 | + print("S3 credentials not available.") |
| 145 | + except Exception as e: |
| 146 | + print(f"Error uploading image to S3: {str(e)}") |
| 147 | + finally: |
| 148 | + # Remove the local image file |
| 149 | + os.remove(image_path) |
| 150 | + |
| 151 | + |
| 152 | +def upload_text_to_s3(text, text_file_path): |
| 153 | + try: |
| 154 | + s3.put_object(Body=text, Bucket=s3_bucket_name, Key=text_file_path) |
| 155 | + except NoCredentialsError: |
| 156 | + print("S3 credentials not available.") |
| 157 | + except Exception as e: |
| 158 | + print(f"Error uploading text file to S3: {str(e)}") |
| 159 | + |
| 160 | + |
| 161 | +def delete_folder_objects(prefix): |
| 162 | + # List objects in the S3 bucket with the specified prefix |
| 163 | + response = s3.list_objects_v2(Bucket=s3_bucket_name, Prefix=prefix) |
| 164 | + |
| 165 | + # Extract the object keys from the response |
| 166 | + objects = [obj["Key"] for obj in response.get("Contents", [])] |
| 167 | + |
| 168 | + # Delete each object |
| 169 | + for obj_key in objects: |
| 170 | + s3.delete_object(Bucket=s3_bucket_name, Key=obj_key) |
| 171 | + |
| 172 | +@router.get("/") |
| 173 | +async def hello(): |
| 174 | + return {"Byte 404 rocks"} |
0 commit comments