ARB Security Solutions, LLC.

Combining SharePoint Online, PyTorch, and Flask

Using a pre-trained ResNet18 model to classify images of cats and dogs, first load the PyTorch model weights from a file stored in a SharePoint Online document library. Then, it defines a Flask app with two routes: one to display a form for uploading an image, and another to receive the uploaded image, preprocess it, pass it through the PyTorch model, and return the classification result as a JSON object.

# Import required libraries
import os
import io
import torch
import torch.nn as nn
import torchvision.models as models
import torchvision.transforms as transforms
from PIL import Image
from flask import Flask, request, jsonify
from office365.runtime.auth.authentication_context import AuthenticationContext
from office365.sharepoint.client_context import ClientContext

# Set up SharePoint Online connection
url = ''
username = '[email protected]'
password = 'yourpassword'
auth_context = AuthenticationContext(url)
auth_context.acquire_token_for_user(username, password)
ctx = ClientContext(url, auth_context)

# Define your PyTorch model
class ImageClassifier(nn.Module):
    def __init__(self, num_classes):
        super(ImageClassifier, self).__init__()
        self.model = models.resnet18(pretrained=True)
        self.model.fc = nn.Linear(self.model.fc.in_features, num_classes)

    def forward(self, x):
        x = self.model(x)
        return x

model_path = 'path/to/your/pytorch/'
num_classes = 2
model = ImageClassifier(num_classes)

# Define your Flask app
app = Flask(__name__)

@app.route('/', methods=['GET'])
def index():
    return '''
    <form method="POST" enctype="multipart/form-data">
        <input type="file" name="file">
        <input type="submit">

@app.route('/', methods=['POST'])
def upload_file():
    file = request.files['file']
    img_bytes =
    img =
    img = transforms.Resize(256)(img)
    img = transforms.CenterCrop(224)(img)
    img = transforms.ToTensor()(img)
    img = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225])(img)
    img = img.unsqueeze(0)
    with torch.no_grad():
        output = model(img)
    result = output.argmax().item()
    if result == 0:
        label = 'Cat'
        label = 'Dog'
    return jsonify({'result': label})

if __name__ == '__main__':

Comments are closed.