0

I use Cloud9 IDE and use default Web server. However the code does not start the server (web server returning: No application seems to be running here!). I double checked every instance of the code, but I am weak at Flask. Flask code was a part of the distribution code.

The code: application.py (that should start the server)

from flask import Flask, redirect, render_template, request, url_for

import sys, helpers
from analyzer import Analyzer

app = Flask(__name__)

@app.route("/")
def index():
    return render_template("index.html")

@app.route("/search")
def search():

    # validate screen_name
    screen_name = request.args.get("screen_name", "")
    if not screen_name:
        return redirect(url_for("index"))

    # get screen_name's tweets
    tweets = helpers.get_user_timeline(screen_name)

    # pass to analyze
    analyzer = Analyzer("positive-words.txt", "negative-words.txt")

    positive, negative, neutral = analyzer.analyze(tweets)

    # generate chart
    chart = helpers.chart(positive, negative, neutral)

    # render results
    return render_template("search.html", chart=chart, screen_name=screen_name)

helpers.py (methods used by application.py):

import html
import os
import plotly
import socket

from twython import Twython
from twython import TwythonAuthError, TwythonError, TwythonRateLimitError

def chart(positive, negative, neutral):
    """Return a pie chart for specified sentiments as HTML."""

    # offline plot
    # https://plot.ly/python/pie-charts/
    # https://plot.ly/python/reference/#pie
    figure = {
        "data": [
            {
                "labels": ["positive", "negative", "neutral"],
                "hoverinfo": "none",
                "marker": {
                    "colors": [
                        "rgb(0,255,00)",
                        "rgb(255,0,0)",
                        "rgb(255,255,0)"
                    ]
                },
                "type": "pie",
                "values": [positive, negative, neutral]
            }
        ],
        "layout": {
            "showlegend": True
            }
    }
    return plotly.offline.plot(figure, output_type="div", show_link=False, link_text=False)

def get_user_timeline(screen_name, count=200):
    """Return list of most recent tweets posted by screen_name."""

    # ensure count is valid
    if count < 1 or count > 200:
        raise RuntimeError("invalid count")

    # ensure environment variables are set
    if not os.environ.get("API_KEY"):
        raise RuntimeError("API_KEY not set")
    if not os.environ.get("API_SECRET"):
        raise RuntimeError("API_SECRET not set")

    # get screen_name's (or @screen_name's) most recent tweets
    # https://dev.twitter.com/rest/reference/get/users/lookup
    # https://dev.twitter.com/rest/reference/get/statuses/user_timeline
    # https://github.com/ryanmcgrath/twython/blob/master/twython/endpoints.py
    try:
        twitter = Twython(os.environ.get("API_KEY"), os.environ.get("API_SECRET"))
        user = twitter.lookup_user(screen_name=screen_name.lstrip("@"))
        if user[0]["protected"]:
            return None
        tweets = twitter.get_user_timeline(screen_name=screen_name, count=count)
        return [html.unescape(tweet["text"].replace("\n", " ")) for tweet in tweets]
    except TwythonAuthError:
        raise RuntimeError("invalid API_KEY and/or API_SECRET") from None
    except TwythonRateLimitError:
        raise RuntimeError("you've hit a rate limit") from None
    except TwythonError:
        return None

analyzer.py (methods used by application.py):

# Tokenizing library 
import nltk

class Analyzer():
    # Defining template for the class with two arguments(file names are not hard coded)
    def __init__(self, positives, negatives):
        # Two dicts for - and + words
        self.positives = {}
        self.negatives = {}
        # Method for reading files into dicts
        def open_file (file_name, dictionary_name):
            with open(file_name) as f:
                # Loop to start with 35th line
                for i in range(35):
                    next(f)
                for line in f:
                    # Keys and values of a dict
                    dictionary_name[line.strip()] = line.strip()
        # Calling methods
        open_file(positives, self.positives)
        open_file(negatives, self.negatives)
    # Analyse tokens  
    def analyze(self, text):
        # Access tools of nltk
        tokenizer = nltk.tokenize.TweetTokenizer()
        # Defining couning score variable
        score_positive = 0
        score_negative = 0
        score_neutral = 0
        # since the text is a list we itterate of the list element by element
        for tweet in text:
            tokens = tokenizer.tokenize(tweet)
            # Checking each token
            for token in tokens:
                if token.lower() in self.positives:
                    score_positive += 1
                elif token.lower() in self.negatives:
                    score_negative += 1
                else:
                    score_neutral += 1
        return score_positive, score_negative, score_neutral

2 Answers 2

2

Add this to your code:

import os

port = int(os.getenv("PORT"))

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=port, debug=True)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you that works! Have no idea though how. At least I have a hint now. Very useful.
You need to make sure to expose your application on the correct port otherwise you won't be able to reach it. Doing just app.run() should work if you start it locally. Instead of initializing the port like I did you could also check which port your application is using and hard code it.
0

Import necessary libraries

from flask import Flask, render_template, request

import numpy as np
import os

from keras.preprocessing.image import load_img
from keras.preprocessing.image import img_to_array
from keras.models import load_model

# load model
model = load_model(r"model/covid_detection.h5")

print('Model loaded successfully')


def pred_cot_dieas(cott_plant):
    test_image = load_img(cott_plant, target_size=(256, 256))  # load image
    print("Image loaded successfully for prediction")

    test_image = img_to_array(test_image) / 255  # convert image to np array and normalize
    test_image = np.expand_dims(test_image, axis=0)  # change dimention 3D to 4D

    result = model.predict(test_image).round(3)  # predict diseased palnt or not
    print('Prediction result = ', result)

    pred = np.argmax(result)  # get the index of max value

    if pred == 0:
        return "Positive", 'covid19.html'  # if index 0 burned leaf
    elif pred == 1:
        return 'Normal', 'normal.html'  # # if index 1
    # elif pred == 2:
    #     return 'Healthy Cotton Plant', 'healthy_plant.html'  # if index 2  fresh leaf
    else:
        return "Pneumonia", 'pneumonia.html'  # if index 3

# 


# Create flask instance
app = Flask(__name__)


# render index.html page
@app.route("/", methods=['GET', 'POST'])
def home():
    return render_template('index.html')


# get input image from client then predict class and render respective .html page for solution
@app.route("/predict", methods=['GET', 'POST'])
def predict():
    if request.method == 'POST':
        file = request.files['image']  # fet input
        filename = file.filename
        print("Input posted = ", filename)

        file_path = os.path.join('static/user upload', filename)
        file.save(file_path)

        print("Predicting class......")
        pred, output_page = pred_cot_dieas(cott_plant=file_path)

        return render_template(output_page, pred_output=pred, user_image=file_path)


# For local system & cloud
if __name__ == "__main__":
    app.run(threaded=False)

Hope this helps

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.