0

Access to fetch at 'http://localhost:5000/image_search?url=https://5fbb4b60e5a371522c26-c46478628be7be7c70f96ec65a31d1c7.ssl.cf3.rackcdn.com/Images/ProductImages/9f0b0638-9ade-46cd-bdaf-284a7dcef792.jpg' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

index.js:

import ProductCard from "@/components/ProductCard/product-card";
import { db, storage, firebase } from "@/config/firebase";
import { useAuth } from "@/firebase/context";
import Layout from "components/Layout";
import Head from "next/head";
import { useState } from "react";

import styles from "./imageSearch.module.scss";

export default function ImageSearch() {
  const { user, loading } = useAuth();
  const [linkVal, setLinkVal] = useState("")
  const [reddata, setData] = useState()
  console.log(user, loading);

  const fetchRecommendations = async (e) => {
    e.preventDefault()
    const data = await fetch(`http://localhost:5000/image_search?url=${linkVal}`).then(res => res.json(),{
      header:{
        'Access-Control-Allow-Origin': 'http://localhost:3000'

      }
    })
    console.log("recommend data ", data)
   
    const recommendIdStrings = []
    data.result.forEach(r => {
      recommendIdStrings.push(r.toString())
    })
   
    console.log("string ids, ",recommendIdStrings)
    await db  
    .collection("Products")
    .where(firebase.firestore.FieldPath.documentId(), "in", recommendIdStrings)
    .get()    
    .then(function (querySnapshot) {
      const products = querySnapshot.docs.map(function (doc) {
        return { id: doc.id, ...doc.data() };
      });
      setData(products);
    })
    .catch((e) => (error = e));

    // setData(data)
  }

  return (<Layout>
    <div className={styles.container}>
      <Head>
        <title>Create Next App</title>
        <link rel="icon" href="/favicon.ico" />
      </Head>
      <main className={styles.main}>
        <div className={styles.header}>
          <h1 className={styles.title}>
            Enter image link to search
          </h1>
        </div>
        <div>
          <div className={styles.uploadForm} >
            {/* <form className={styles.form} >
              <progress id="uploader" value="0" max="100">{uploaderVal}%</progress>
        <input onChange={uploadToFirebase} type="file" id="fileButton" />
              </form> */}

            <input onChange={e => setLinkVal(e.target.value)} value={linkVal} type="text" id="imageUrl" />
            <button onClick={fetchRecommendations} > Search</button>
          </div>
        </div>
        <div className={styles.products}>
            {!loading && reddata &&
              reddata.map((product) => {
                return (
                  <ProductCard
                    key={product.id}
                    id={product.id}
                    brand={product.sellers}
                    name={product.productDisplayName}
                    image={product.link}
                    price={product.price + 142}
                    sale_price={product.price}
                    favorite={user?.favorites?.includes(product.id)}
                  />
                );
              })}
          </div>
      </main>
    </div>
  </Layout>
  )
}

app.py:

from flask import Flask,request,jsonify, Response
import pickle
import numpy as np
from numpy.linalg import norm
import urllib.request
import os
import tensorflow 
from tensorflow.keras.preprocessing import image
from tensorflow.keras.layers import GlobalMaxPooling2D
from tensorflow.keras.applications.resnet50 import ResNet50,preprocess_input
from sklearn.neighbors import NearestNeighbors
import pandas as pd
from transformers import pipeline
from flask_cors import CORS, cross_origin



model = ResNet50(weights='imagenet',include_top=False,input_shape=(224,224,3))
model.trainable = False
model = tensorflow.keras.Sequential([
                          model,
                          GlobalMaxPooling2D()
])

def extract_features(img_path,model):
  img = image.load_img(img_path,target_size=(224,224))
  img_array = image.img_to_array(img)
  expanded_img_array = np.expand_dims(img_array,axis=0) 
  preprocessed_img = preprocess_input(expanded_img_array)
  result = model.predict(preprocessed_img).flatten()
  normalized_result = result/norm(result)
  return normalized_result

feature_list = pickle.load(open('embeddings.pkl','rb'))
filenames = pickle.load(open('filenames.pkl','rb'))

neighbors = NearestNeighbors(n_neighbors=6,algorithm='brute',metric='euclidean')
neighbors.fit(feature_list)

app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'


@app.route('/',methods=['GET'])
@cross_origin()
def helloworld():
    return jsonify({'response': "Hello World"})

@app.route('/recommend',methods=['GET'])
@cross_origin()
def index():
    args = request.args
    path = args['name']
    id = args['id']
    
    urllib.request.urlretrieve(path, "./uploads/"+str(id)+".jpg")
    result = extract_features("./uploads/"+str(id)+'.jpg',model)
    distances,indices = neighbors.kneighbors([result])
    final_Arr = []
    for i in indices[0]:
        final_Arr.append(int(str(filenames[i].split('/')[-1].split('.')[0])))
       
    os.remove("./uploads/"+str(id)+'.jpg')
    return jsonify({'result': final_Arr})



@app.route('/image_search')
@cross_origin()
def imagesearch():
    args = request.args
    url = args['url']
    urllib.request.urlretrieve(url, "./uploads/" + "test.jpg")
    result = extract_features("./uploads/"+'test.jpg',model)
    distances,indices = neighbors.kneighbors([result])
    final_Arr = []
    for i in indices[0]:
        final_Arr.append(int(str(filenames[i].split('/')[-1].split('.')[0])))
       
    os.remove("./uploads/"+'test.jpg')


    return jsonify({'result': final_Arr})


@app.route('/search')
@cross_origin()
def search():
    args = request.args
    query = args['query']
    df = pd.read_csv('./grandfinaleX.csv',error_bad_lines = False)

    lis = ['gender','masterCategory','subCategory','articleType','productDisplayName']
    temp_df = pd.DataFrame()
    for col in lis:
        temp_df[col] = df[col].apply(lambda x : str(x).lower())

    temp_df['id'] = df['id']

    x_df = pd.DataFrame()

    for i in query.split():
        for j in lis:
            new_df = pd.DataFrame()

            new_df = temp_df[temp_df[j] == i]
            x_df = pd.concat([x_df,new_df])

    arr = x_df['id'].head(10).values
    # Just want to see how it's returning the json file
    print(jsonify({'searchResult': arr.tolist()}))
    return jsonify({'searchResult': arr.tolist()})

@app.route('/sentiment')
def sentiment():
    sentiment_pipeline = pipeline("sentiment-analysis")
    data = ["I love you"]
    print(sentiment_pipeline(data))
    return "Hello Bro"



if __name__ == '__main__':
    app.run(debug=True)

It should fetch the jpg.

AriC
  • 1
  • 1

0 Answers0