myspace / app.py
naliveli's picture
Update app.py
1ddb0bf
Raw History Blame Contribute Delete
1.98 kB
from fastai.vision.all import *
import gradio as gr
from transformers import pipeline
from duckduckgo_search import ddg_images
def search_images(term, max_images=30):
print(f"Searching for '{term}'")
return L(ddg_images(term, max_results=max_images)).itemgot('image')
urls = search_images('animal photos', max_images=1)
urls[0]
from fastdownload import download_url
dest = 'animal.jpg'
download_url(urls[0], dest, show_progress=True)
from fastai.vision.all import *
im = Image.open(dest)
im.to_thumb(256,256)
download_url(search_images('desert pictures', max_images=1)[0], 'desert.jpg', show_progress=True)
#Image.open('desert.jpg').to_thumb(256,256)
searches = 'desert','animal'
path = Path('animal_or_not')
from time import sleep
for o in searches:
dest = (path/o)
dest.mkdir(exist_ok=True, parents=True)
download_images(dest, urls=search_images(f'{o} photo'))
sleep(10) # Pause between searches to avoid over-loading server
download_images(dest, urls=search_images(f'{o} sunny photo'))
sleep(10)
download_images(dest, urls=search_images(f'{o} moon light photo'))
sleep(10)
resize_images(path/o, max_size=400, dest=path/o)
failed = verify_images(get_image_files(path))
failed.map(Path.unlink)
len(failed)
dls = DataBlock(
blocks=(ImageBlock, CategoryBlock),
get_items=get_image_files,
splitter=RandomSplitter(valid_pct=0.2, seed=42),
get_y=parent_label,
item_tfms=[Resize(192, method='squish')]
).dataloaders(path, bs=32)
dls.show_batch(max_n=6)
learn = vision_learner(dls, resnet18, metrics=error_rate)
learn.fine_tune(2)
# Step 3: Create a prediction function
def classify_image(inp):
img = PILImage.create(inp)
pred, pred_idx, probs = learn.predict(img)
return f'Prediction: {pred}; Probability: {probs[pred_idx]*100:.2f}%'
# Step 4: Create the Gradio interface
iface = gr.Interface(fn=classify_image, inputs="image", outputs="text")
# Step 5: Launch the interface
iface.launch()