Py4JJavaError on a Spark Session on Windows

161 Views Asked by At

I have a code who working very well on google colab :

Path :

PATH = os.getcwd()
PATH_Data = '/content/drive/MyDrive/Formation Data Science/Projet N°8 Septembre 2023/TestLocal' # Vu qu'il manque le fichier restrain j'ai pris un dossier au pif pour tester le modèle.
PATH_Result = PATH+'/content/drive/MyDrive/Formation Data Science/Projet N°8 Septembre 2023' # Emplacement de téléchargement du fichier final.

# Impression des PATH pour vérification :
print('PATH:        '+\
      PATH+'\nPATH_Data:   '+\
      PATH_Data+'\nPATH_Result: '+PATH_Result)

Spark Session :

# Création de la session en local, avec un format définit et un nom choisi :
spark = SparkSession.builder.appName('P8').master('local').config("spark.sql.parquet.writeLegacyFormat", 'true').getOrCreate()

# Création du sparx contexte : Le SparkContext est le point d'entrée pour utiliser les fonctionnalités de Spark.
sc = spark.sparkContext

# Informations sur la session Spark créée :
spark

The only problem I have here is when I click on SPARK UI I have an error (but my data are ok at the end of my code)

Extract Path of my pictures (1Mo) :

# Chargement des données avec la bonne extention et dans tous les sous dossiers :
images = spark.read.format("binaryFile").option("pathGlobFilter", "*.jpg").option("recursiveFileLookup", "true").load(PATH_Data)
images = images.withColumn('label', element_at(split(images['path'], '/'),-2))

# impression des résultats :
print(images.select('path','label').show(5, False))

And after that I have my model MobilNetV2 and a PCA ==> everithing was ok.

But I need to do the same things in local on my Jupyter Notebook :

PATH :

PATH = os.getcwd()
PATH_Data = "C:/Users/Johan/Formation Data Science/Projet 8/DonneesLocales/TestLocal" # Vu qu'il manque le fichier restrain j'ai créé un dossier au pif pour tester le modèle.
PATH_Result = PATH # Emplacement de téléchargement du fichier final.

# Impression des PATH pour vérification :
print('PATH:        '+\
      PATH+'\nPATH_Data:   '+\
      PATH_Data+'\nPATH_Result: '+PATH_Result)

==> Everithing was ok for this step.

SPARK Session :

# Création de la session en local, avec un format définit et un nom choisi :
spark = SparkSession.builder.appName('P8').master('local').config("spark.sql.parquet.writeLegacyFormat", 'true').config("spark.driver.memory", "2g").config("spark.executor.memory", "2g").config("spark.executor.cores", "4").getOrCreate()

# Création du sparx contexte : Le SparkContext est le point d'entrée pour utiliser les fonctionnalités de Spark.
sc = spark.sparkContext

# Informations sur la session Spark créée :
spark

==> Everithing was ok with this step I have my spark session and I can see the SPARK UI on 4040 or 4041

Extract PATH of my picture :

The problems start here :

If I use that for one picture this is OK :

image_path = "C:/Users/Johan/Formation Data Science/Projet 8/DonneesLocales/TestLocal/Apple Golden 1/72_100.jpg"


# Chargement des données avec la bonne extention et dans tous les sous dossiers :
images = spark.read.format("binaryFile").option("pathGlobFilter", "*.jpg").option("recursiveFileLookup", "true").load(image_path)
images = images.withColumn('label', element_at(split(images['path'], '/'),-2))

# impression des résultats :
print(images.select('path','label').show(5, False))

# Afficher les 5 dernières lignes du DataFrame
images.select('path', 'label').orderBy(images['path'].desc()).show(5, False)

# Explication des données :
print(images.printSchema())

But If I use that for my file I have an error :

image_path = "C:/Users/Johan/Formation Data Science/Projet 8/DonneesLocales/TestLocal/Apple Golden 1/"


# Chargement des données avec la bonne extention et dans tous les sous dossiers :
images = spark.read.format("binaryFile").option("pathGlobFilter", "*.jpg").option("recursiveFileLookup", "true").load(image_path)
images = images.withColumn('label', element_at(split(images['path'], '/'),-2))

# impression des résultats :
print(images.select('path','label').show(5, False))

# Afficher les 5 dernières lignes du DataFrame
images.select('path', 'label').orderBy(images['path'].desc()).show(5, False)

# Explication des données :
print(images.printSchema())

This is the same code than in google colab (and I tried without the Apple Golden but I have the same error) The error :

---------------------------------------------------------------------------
Py4JJavaError                             Traceback (most recent call last)
Cell In[11], line 5
      1 image_path = "C:/Users/Johan/Formation Data Science/Projet 8/DonneesLocales/TestLocal/Apple Golden 1/"
      4 # Chargement des données avec la bonne extention et dans tous les sous dossiers :
----> 5 images = spark.read.format("binaryFile").option("pathGlobFilter", "*.jpg").option("recursiveFileLookup", "true").load(image_path)
      6 images = images.withColumn('label', element_at(split(images['path'], '/'),-2))
      8 # impression des résultats :

File ~\anaconda3\Lib\site-packages\pyspark\sql\readwriter.py:307, in DataFrameReader.load(self, path, format, schema, **options)
    305 self.options(**options)
    306 if isinstance(path, str):
--> 307     return self._df(self._jreader.load(path))
    308 elif path is not None:
    309     if type(path) != list:

File ~\anaconda3\Lib\site-packages\py4j\java_gateway.py:1322, in JavaMember.__call__(self, *args)
   1316 command = proto.CALL_COMMAND_NAME +\
   1317     self.command_header +\
   1318     args_command +\
   1319     proto.END_COMMAND_PART
   1321 answer = self.gateway_client.send_command(command)
-> 1322 return_value = get_return_value(
   1323     answer, self.gateway_client, self.target_id, self.name)
   1325 for temp_arg in temp_args:
   1326     if hasattr(temp_arg, "_detach"):

File ~\anaconda3\Lib\site-packages\pyspark\errors\exceptions\captured.py:179, in capture_sql_exception.<locals>.deco(*a, **kw)
    177 def deco(*a: Any, **kw: Any) -> Any:
    178     try:
--> 179         return f(*a, **kw)
    180     except Py4JJavaError as e:
    181         converted = convert_exception(e.java_exception)

File ~\anaconda3\Lib\site-packages\py4j\protocol.py:326, in get_return_value(answer, gateway_client, target_id, name)
    324 value = OUTPUT_CONVERTER[type](answer[2:], gateway_client)
    325 if answer[1] == REFERENCE_TYPE:
--> 326     raise Py4JJavaError(
    327         "An error occurred while calling {0}{1}{2}.\n".
    328         format(target_id, ".", name), value)
    329 else:
    330     raise Py4JError(
    331         "An error occurred while calling {0}{1}{2}. Trace:\n{3}\n".
    332         format(target_id, ".", name, value))

Py4JJavaError: An error occurred while calling o144.load.
: java.lang.UnsatisfiedLinkError: 'boolean org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(java.lang.String, int)'
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access0(Native Method)
    at org.apache.hadoop.io.nativeio.NativeIO$Windows.access(NativeIO.java:793)
    at org.apache.hadoop.fs.FileUtil.canRead(FileUtil.java:1249)
    at org.apache.hadoop.fs.FileUtil.list(FileUtil.java:1454)
    at org.apache.hadoop.fs.RawLocalFileSystem.listStatus(RawLocalFileSystem.java:601)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:1972)
    at org.apache.hadoop.fs.FileSystem.listStatus(FileSystem.java:2014)
    at org.apache.hadoop.fs.ChecksumFileSystem.listStatus(ChecksumFileSystem.java:761)
    at org.apache.spark.util.HadoopFSUtils$.listLeafFiles(HadoopFSUtils.scala:180)
    at org.apache.spark.util.HadoopFSUtils$.$anonfun$parallelListLeafFilesInternal$1(HadoopFSUtils.scala:95)
    at scala.collection.TraversableLike.$anonfun$map$1(TraversableLike.scala:286)
    at scala.collection.mutable.ResizableArray.foreach(ResizableArray.scala:62)
    at scala.collection.mutable.ResizableArray.foreach$(ResizableArray.scala:55)
    at scala.collection.mutable.ArrayBuffer.foreach(ArrayBuffer.scala:49)
    at scala.collection.TraversableLike.map(TraversableLike.scala:286)
    at scala.collection.TraversableLike.map$(TraversableLike.scala:279)
    at scala.collection.AbstractTraversable.map(Traversable.scala:108)
    at org.apache.spark.util.HadoopFSUtils$.parallelListLeafFilesInternal(HadoopFSUtils.scala:85)
    at org.apache.spark.util.HadoopFSUtils$.parallelListLeafFiles(HadoopFSUtils.scala:69)
    at org.apache.spark.sql.execution.datasources.InMemoryFileIndex$.bulkListLeafFiles(InMemoryFileIndex.scala:162)
    at org.apache.spark.sql.execution.datasources.InMemoryFileIndex.listLeafFiles(InMemoryFileIndex.scala:133)
    at org.apache.spark.sql.execution.datasources.InMemoryFileIndex.refresh0(InMemoryFileIndex.scala:96)
    at org.apache.spark.sql.execution.datasources.InMemoryFileIndex.<init>(InMemoryFileIndex.scala:68)
    at org.apache.spark.sql.execution.datasources.DataSource.createInMemoryFileIndex(DataSource.scala:539)
    at org.apache.spark.sql.execution.datasources.DataSource.resolveRelation(DataSource.scala:405)
    at org.apache.spark.sql.DataFrameReader.loadV1Source(DataFrameReader.scala:229)
    at org.apache.spark.sql.DataFrameReader.$anonfun$load$2(DataFrameReader.scala:211)
    at scala.Option.getOrElse(Option.scala:189)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:211)
    at org.apache.spark.sql.DataFrameReader.load(DataFrameReader.scala:186)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.base/java.lang.reflect.Method.invoke(Method.java:566)
    at py4j.reflection.MethodInvoker.invoke(MethodInvoker.java:244)
    at py4j.reflection.ReflectionEngine.invoke(ReflectionEngine.java:374)
    at py4j.Gateway.invoke(Gateway.java:282)
    at py4j.commands.AbstractCommand.invokeMethod(AbstractCommand.java:132)
    at py4j.commands.CallCommand.execute(CallCommand.java:79)
    at py4j.ClientServerConnection.waitForCommands(ClientServerConnection.java:182)
    at py4j.ClientServerConnection.run(ClientServerConnection.java:106)
    at java.base/java.lang.Thread.run(Thread.java:829)

In fact this code works :

import glob

# Spécifiez le chemin du dossier parent
dossier_parent = "C:/Users/Johan/Formation Data Science/Projet 8/DonneesLocales/TestLocal/"

# Utilisez glob pour trouver tous les fichiers .jpg dans le dossier parent et ses sous-dossiers
fichiers_jpg = glob.glob(os.path.join(dossier_parent, "**/*.jpg"), recursive=True)

fichiers_jpg
from pyspark.sql.functions import udf
from pyspark.sql.types import StringType

# Définir la fonction UDF pour supprimer le préfixe "file:/"
@udf(StringType())
def remove_file_prefix(path):
    return path.replace('file:/', '')

# Créer la session Spark
spark = SparkSession.builder.appName("ImageLoading").getOrCreate()

# Charger les données avec la bonne extension et dans tous les sous-dossiers
images = spark.read.format("binaryFile").option("pathGlobFilter", "*.jpg").option("recursiveFileLookup", "true").load(fichiers_jpg)

# Ajouter la colonne 'label' en utilisant les fonctions element_at et split
images = images.withColumn('label', element_at(split(images['path'], '/'), -2))

# Utiliser la fonction UDF pour supprimer le préfixe "file:/"
images = images.withColumn('path', remove_file_prefix(images['path']))

# Afficher les 5 premières lignes du DataFrame
print(images.select('path', 'label').show(5, False))

# Afficher les 5 dernières lignes du DataFrame
images.select('path', 'label').orderBy(images['path'].desc()).show(5, False)

# Explication des données
print(images.printSchema())

But if I have 50000 picture I guess it will be to heavy. And I have an another Py4JJavaError when I used my machine learning modèle.

I have :

  • Windows 10.
  • Spark 3.5.0 on jupyter notebook and Google Colab.
  • Pyspark 3.5.0 on both.
  • py4j 0.10.9.7 on both.
  • Java :
    • Google Colab : Version de Java détectée : openjdk version "11.0.20.1" 2023-08-24
    • Jupyter Notebook : Version de Java détectée : openjdk version "11.0.20.1" 2023-08-24 LTS
  • Python :
    • Google Colab : 3.10.12 (main, Jun 11 2023, 05:26:28) [GCC 11.4.0]
    • Jupyter notebook : 3.11.4 | packaged by Anaconda, Inc. | (main, Jul 5 2023, 13:38:37) [MSC v.1916 64 bit (AMD64)]
  • winutils.exe in my computer : 3.0.0

Path :

  • C:\Program Files\Java\jdk11\bin

  • C:\Program Files\Spark\spark-bin-hadoop3\bin

  • C:\Program Files\Spark\winutils\bin

  • HADOOP_HOME : C:\Program Files\Spark\winutils

  • JAVA_HOME : C:\Program Files\Java\jdk11

  • PYSPARK_PYTHON : C:\Users\Johan\anaconda3\python.exe

  • SPARK_HOME : C:\Program Files\Spark\spark-bin-hadoop3

I don't know how I can correct my mistake I tried many things a found on internet. Maybe my computer is not enought powerful??? Or this is the version of python but i am on anaconda and i don't have a virtual environnement.

0

There are 0 best solutions below