[Python] Permission Denied Issue in Gradio

Discussão em 'Python' iniciado por Stack, Fevereiro 25, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to create a gradio app which was working before now i have added the image functionality which analyzes the image and for text analysis the app was working fine but now it gives permission error:

    import gradio as gr
    from image import ImageAnalyzer
    from cleaning import cleanText
    from translate import translate_to_english
    from sentiment import SentimentClassifier
    from emotion import EmotionClassifier
    from toxic import ToxicityClassifier
    from racist import RacistClassifier

    def classify_confidence(score):
    if score >= 75:
    return "High"
    elif score >= 50:
    return "Medium"
    else:
    return "Low"

    def analyze_text(user_input):
    try:
    sentimentAnalyzer = SentimentClassifier()
    emotionAnalyzer = EmotionClassifier()
    toxicityAnalyzer = ToxicityClassifier()
    racismAnalyzer = RacistClassifier()

    cleanedText = cleanText(user_input)
    translatedText = translate_to_english(cleanedText)

    sentimentResult = sentimentAnalyzer.predict_sentiment(translatedText)
    emotionResult = emotionAnalyzer.classifyEmotion(translatedText)
    toxicResult = toxicityAnalyzer.predict(translatedText)
    racismResult = racismAnalyzer.predict(translatedText)

    # Processing sentiment results
    sentiment_data = "\n".join(
    [f"{label}: {data['confidence']}%" for label, data in sentimentResult.items()]
    )

    # Getting top 3 emotions without confidence classification
    sorted_emotions = sorted(emotionResult.items(), key=lambda x: x[1], reverse=True)
    top3_emotions = "\n".join(
    [f"{emotion}: {score:.2f}%" for emotion, score in sorted_emotions[:3]]
    )

    # Processing toxicity and racism analysis with confidence classification
    toxicity_analysis = "\n".join(
    [f"{label}: {score:.2f}% ({classify_confidence(score)})" for label, score in toxicResult.items()]
    )
    racism_analysis = "\n".join(
    [f"{label}: {score:.2f}% ({classify_confidence(score)})" for label, score in racismResult.items()]
    )

    return cleanedText, translatedText, sentiment_data, top3_emotions, toxicity_analysis, racism_analysis
    except Exception as e:
    return "", "", "", "", "", f"Unexpected error: {e}"

    def analyze_image(image):
    try:
    analyzer = ImageAnalyzer()
    return analyzer.def_image(image)
    except Exception as e:
    return "", "", f"Unexpected error: {e}"

    def process_inputs(text, image):
    if text and not image:
    return analyze_text(text) + ("", "", "") # Empty placeholders for image outputs
    elif image and not text:
    return ("", "", "", "", "", "") + analyze_image(image) # Empty placeholders for text outputs
    elif text and image:
    return analyze_text(text) + analyze_image(image)
    else:
    return ("", "", "", "", "", "", "", "", "") # Empty results for both text and image inputs

    def main():
    interface = gr.Interface(
    fn=process_inputs,
    inputs=[gr.Textbox(lines=3, placeholder="Enter text to analyze..."), gr.Image(type="pil")],
    outputs=[
    gr.Textbox(label="Cleaned Text"),
    gr.Textbox(label="Translated Text"),
    gr.Textbox(label="Sentiment Analysis", lines=3),
    gr.Textbox(label="Top 3 Emotion Detection", lines=3),
    gr.Textbox(label="Toxicity Analysis", lines=3),
    gr.Textbox(label="Racism Analysis", lines=3),
    gr.Textbox(label="Image Analysis Results"),
    gr.Image(label="ELA Image"),
    gr.Image(label="Highlighted Forgery Image")
    ],
    title="Text and Image Analysis Demo",
    description="Analyze text for sentiment, emotions, toxicity, racism, and detect image forgery using AI models.",
    )

    interface.launch()

    if __name__ == "__main__":
    main()


    and this is my code of ImageAnalyzer that i added:

    import cv2
    import numpy as np
    from PIL import Image, ImageChops, ImageEnhance, UnidentifiedImageError
    import os
    import tensorflow as tf
    import binascii

    class ImageAnalyzer:
    def __init__(self, model_path="../scripts/results/image/Model-2/MobileNetV2.keras"):
    self.model = tf.keras.models.load_model(model_path)

    def generate_unique_filename(self, extension=".jpg"):
    return binascii.hexlify(os.urandom(8)).decode() + extension

    def perform_ela(self, image_path, quality=90, threshold=30, save_path="output/"):
    if not os.path.exists(save_path):
    os.makedirs(save_path)

    unique_filename = self.generate_unique_filename(".jpg")
    temp_path = os.path.join(save_path, unique_filename)

    original = Image.open(image_path).convert("RGB")
    original.save(temp_path, "JPEG", quality=quality)
    compressed = Image.open(temp_path)

    ela_image = ImageChops.difference(original, compressed)
    extrema = ela_image.getextrema()
    max_diff = max([ex[1] for ex in extrema])

    if max_diff == 0:
    max_diff = 1

    scale = 255.0 / max_diff
    ela_image = ImageEnhance.Brightness(ela_image).enhance(scale)
    ela_image_path = os.path.join(save_path, self.generate_unique_filename(".png"))
    ela_image.save(ela_image_path)

    ela_cv = cv2.imread(ela_image_path)
    gray = cv2.cvtColor(ela_cv, cv2.COLOR_BGR2GRAY)
    _, thresh = cv2.threshold(gray, threshold, 255, cv2.THRESH_BINARY)

    total_pixels = thresh.size
    forged_pixels = np.count_nonzero(thresh)
    forged_percentage = (forged_pixels / total_pixels) * 100

    highlight_path = os.path.join(save_path, self.generate_unique_filename(".png"))
    cv2.imwrite(highlight_path, thresh)

    is_forged = "Yes" if forged_percentage > 0.5 else "No"

    return {
    "forged": is_forged,
    "percentage": round(forged_percentage, 2),
    "ela_image": ela_image_path,
    "highlighted_image": highlight_path
    }

    def predict_image(self, image_path):
    image = Image.open(image_path).resize((224, 224))
    image = np.array(image) / 255.0
    image = np.expand_dims(image, axis=0)

    prediction = self.model.predict(image)[0]
    confidence_real = prediction[0]
    confidence_fake = prediction[1]

    label = "Real" if confidence_real > confidence_fake else "Fake"
    confidence = max(confidence_real, confidence_fake) * 100

    return {"label": label, "confidence": round(confidence, 2)}

    def def_image(self, image):
    try:
    if not isinstance(image, Image.Image):
    raise ValueError("Invalid image format. Please upload a valid image file.")

    # Convert to RGB to remove alpha channels and ensure compatibility
    image = image.convert("RGB")

    # Save image as a temporary JPEG file
    image_path = "image/temp_image.jpg"
    image.save(image_path, format="JPEG")

    # Perform ELA analysis and prediction
    ela_result = self.perform_ela(image_path)
    prediction_result = self.predict_image(image_path)

    return {
    "forged": ela_result["forged"],
    "percentage": ela_result["percentage"],
    "ela_image": ela_result["ela_image"],
    "highlighted_image": ela_result["highlighted_image"],
    "prediction_label": prediction_result["label"],
    "prediction_confidence": prediction_result["confidence"]
    }

    except UnidentifiedImageError:
    raise ValueError("Corrupt or unsupported image file. Please upload a valid image.")
    except Exception as e:
    raise ValueError(f"An unexpected error occurred: {e}")



    Error:

    PermissionError: [Errno 13] Permission denied: 'D:\\Uni\\FYP\\Model\\model\\Demo_Gradio'

    I have tried creating a new directory and also made changes in the code but nothing really worked so far.

    Continue reading...

Compartilhe esta Página