ModuleNotFoundError: No module named 'torch'

I am getting the torch error while deploying app on streamlit. On Local machine i am using conda python 3.10 and everything working fine. but on streamlit I have added all requirements.txt dependencies but I get error everytime same.

Code snippet:

import streamlit as st
import os
import shutil
import torch
# import cv2
from PIL import Image
from io import BytesIO

model = torch.hub.load(
    "AK391/animegan2-pytorch:main",
    "generator",
    pretrained=True,
    device="cpu",
    progress=False
)


face2paint = torch.hub.load(
    'AK391/animegan2-pytorch:main', 'face2paint', 
    size=512, device="cpu",side_by_side=False
)

st.title("Cartoonify Image")

method = st.sidebar.selectbox("Select method", ["Cartoonify AnimeGanV2", "Cartoonify by CartoonGAN"])

if method == "Cartoonify AnimeGanV2":
    face2paint_check = st.sidebar.checkbox("Enable Face2Paint", False)

uploaded_file = st.file_uploader("Choose an image...", type=["jpg", "jpeg", "png"])

if uploaded_file is not None:
    try:
        img = Image.open(BytesIO(uploaded_file.read()))
        st.image(img, caption='Original Image', use_column_width=True)

        if method == "Cartoonify AnimeGanV2":
            if face2paint_check:
                out = face2paint(model, img)
            else:
                out = model(img)

        else:
            if not os.path.exists('temp'):
                os.makedirs('temp')
            img.save("temp/image.jpg", "JPEG")
            os.system("python cartoon.py --input_path 'temp/image.jpg'  --result_dir './output/'")
            out = Image.open("output/image.jpg")

        st.image(out, caption='Cartoonified Image', use_column_width=True)

        # Save output image to file
        out_path = f"output/{method}.jpg"
        out.save(out_path, "JPEG")

        st.success(f"Output image saved to {out_path}")

    except Exception as e:
        st.error(str(e))

this is image to cartoon converter code. I want to upload it on streamlit to make api later.
but everytime I run I got the error

2023-03-23 18:27:51.154 Uncaught app exception
Traceback (most recent call last):
  File "/home/appuser/venv/lib/python3.10/site-packages/streamlit/runtime/scriptrunner/script_runner.py", line 565, in _run_script
    exec(code, module.__dict__)
  File "/app/face/fl.py", line 4, in <module>
    import torch
ModuleNotFoundError: No module named 'torch'
  • Streamlit version: (latest install now)
  • Python version: (3.10)

Github Repo

https://github.com/datafinderservice/face/blob/main/requirements.txt

1 Like

In my case, I also had to add torchvision to requirements.txt

This topic was automatically closed 365 days after the last reply. New replies are no longer allowed.