Learning FLask: Stuck at OpenAI api

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from flask import Flask, request, jsonify, send_from_directory
import openai
from openai import OpenAI
import os
app = Flask(__name__)
openai.api_key = 'sk-' # I added my key here.
@app.route('/')
def index():
return send_from_directory('.', 'index.html')
@app.route('/analyze', methods=['POST'])
def analyze_cv():
if 'cv' not in request.files or 'job_description' not in request.files:
return jsonify({'error': 'CV and Job Description files are required'}), 400
cv = request.files['cv'].read()
job_description = request.files['job_description'].read()
try:
cv = cv.decode('utf-8')
except UnicodeDecodeError:
cv = cv.decode('latin-1')
try:
job_description = job_description.decode('utf-8')
except UnicodeDecodeError:
job_description = job_description.decode('latin-1')
prompt = f"Given the following job description:n{job_description}nnAssess the suitability of the candidate based on the CV:n{cv}nnScore the candidate from 1 to 10 and provide an explanation."
try:
client = OpenAI(api_key = os.environ.get("OPENAI_API_KEY"),)
openai.Completion.create
response = client.Completions.create(
engine="text-davinci-003",
prompt=prompt,
temperature=0.7,
max_tokens=1024
)
score = int(response.choices[0].text.split()[0])
explanation = response.choices[0].text.split('n')[1]
return jsonify({'score': score, 'explanation': explanation}), 200
except Exception as e:
print(e)
return jsonify({'error': 'An error occurred while analyzing the CV'}), 500
if __name__ == '__main__':
app.run(debug=True)
</code>
<code>from flask import Flask, request, jsonify, send_from_directory import openai from openai import OpenAI import os app = Flask(__name__) openai.api_key = 'sk-' # I added my key here. @app.route('/') def index(): return send_from_directory('.', 'index.html') @app.route('/analyze', methods=['POST']) def analyze_cv(): if 'cv' not in request.files or 'job_description' not in request.files: return jsonify({'error': 'CV and Job Description files are required'}), 400 cv = request.files['cv'].read() job_description = request.files['job_description'].read() try: cv = cv.decode('utf-8') except UnicodeDecodeError: cv = cv.decode('latin-1') try: job_description = job_description.decode('utf-8') except UnicodeDecodeError: job_description = job_description.decode('latin-1') prompt = f"Given the following job description:n{job_description}nnAssess the suitability of the candidate based on the CV:n{cv}nnScore the candidate from 1 to 10 and provide an explanation." try: client = OpenAI(api_key = os.environ.get("OPENAI_API_KEY"),) openai.Completion.create response = client.Completions.create( engine="text-davinci-003", prompt=prompt, temperature=0.7, max_tokens=1024 ) score = int(response.choices[0].text.split()[0]) explanation = response.choices[0].text.split('n')[1] return jsonify({'score': score, 'explanation': explanation}), 200 except Exception as e: print(e) return jsonify({'error': 'An error occurred while analyzing the CV'}), 500 if __name__ == '__main__': app.run(debug=True) </code>
from flask import Flask, request, jsonify, send_from_directory
import openai
from openai import OpenAI
import os

app = Flask(__name__)


openai.api_key = 'sk-' # I added my key here.

@app.route('/')
def index():
    return send_from_directory('.', 'index.html')

@app.route('/analyze', methods=['POST'])
def analyze_cv():
    if 'cv' not in request.files or 'job_description' not in request.files:
        return jsonify({'error': 'CV and Job Description files are required'}), 400

    cv = request.files['cv'].read()
    job_description = request.files['job_description'].read()

    try:
        cv = cv.decode('utf-8')
    except UnicodeDecodeError:
        cv = cv.decode('latin-1')

    try:
        job_description = job_description.decode('utf-8')
    except UnicodeDecodeError:
        job_description = job_description.decode('latin-1')


    prompt = f"Given the following job description:n{job_description}nnAssess the suitability of the candidate based on the CV:n{cv}nnScore the candidate from 1 to 10 and provide an explanation."


    try:
        client = OpenAI(api_key = os.environ.get("OPENAI_API_KEY"),)
        openai.Completion.create
        response = client.Completions.create(
            engine="text-davinci-003",
            prompt=prompt,
            temperature=0.7,
            max_tokens=1024
        )

        score = int(response.choices[0].text.split()[0])
        explanation = response.choices[0].text.split('n')[1]

        return jsonify({'score': score, 'explanation': explanation}), 200
    
    except Exception as e:
        print(e)  
        return jsonify({'error': 'An error occurred while analyzing the CV'}), 500

if __name__ == '__main__':
    app.run(debug=True)
Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CV Analyzer</title>
</head>
<body>
<h1>CV Analyzer</h1>
<input type="file" id="cv" accept=".pdf,.doc,.docx">
<input type="file" id="job_description" accept=".pdf,.txt,.doc,.docx">
<button onclick="analyze()">Analyze</button>
<div id="result"></div>
<script>
function analyze() {
var cvFile = document.getElementById('cv').files[0];
var jobDescriptionFile = document.getElementById('job_description').files[0];
if (!cvFile || !jobDescriptionFile) {
alert('Please upload both CV and Job Description files.');
return;
}
var formData = new FormData();
formData.append('cv', cvFile);
formData.append('job_description', jobDescriptionFile);
fetch('/analyze', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
document.getElementById('result').innerHTML = `
<h2>Score: ${data.score}</h2>
<p>${data.explanation}</p>
`;
})
.catch(error => console.error('Error:', error));
}
</script>
</body>
</html>
</code>
<code><!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CV Analyzer</title> </head> <body> <h1>CV Analyzer</h1> <input type="file" id="cv" accept=".pdf,.doc,.docx"> <input type="file" id="job_description" accept=".pdf,.txt,.doc,.docx"> <button onclick="analyze()">Analyze</button> <div id="result"></div> <script> function analyze() { var cvFile = document.getElementById('cv').files[0]; var jobDescriptionFile = document.getElementById('job_description').files[0]; if (!cvFile || !jobDescriptionFile) { alert('Please upload both CV and Job Description files.'); return; } var formData = new FormData(); formData.append('cv', cvFile); formData.append('job_description', jobDescriptionFile); fetch('/analyze', { method: 'POST', body: formData }) .then(response => response.json()) .then(data => { document.getElementById('result').innerHTML = ` <h2>Score: ${data.score}</h2> <p>${data.explanation}</p> `; }) .catch(error => console.error('Error:', error)); } </script> </body> </html> </code>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CV Analyzer</title>
</head>
<body>
    <h1>CV Analyzer</h1>
    <input type="file" id="cv" accept=".pdf,.doc,.docx">
    <input type="file" id="job_description" accept=".pdf,.txt,.doc,.docx">
    <button onclick="analyze()">Analyze</button>
    <div id="result"></div>

    <script>
        function analyze() {
            var cvFile = document.getElementById('cv').files[0];
            var jobDescriptionFile = document.getElementById('job_description').files[0];

            if (!cvFile || !jobDescriptionFile) {
                alert('Please upload both CV and Job Description files.');
                return;
            }

            var formData = new FormData();
            formData.append('cv', cvFile);
            formData.append('job_description', jobDescriptionFile);

            fetch('/analyze', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                document.getElementById('result').innerHTML = `
                    <h2>Score: ${data.score}</h2>
                    <p>${data.explanation}</p>
                `;
            })
            .catch(error => console.error('Error:', error));
        }
    </script>
</body>
</html>

So I coded the above two file. But I am unable to get the “Score”.
On console this error pops up again and again:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable
127.0.0.1 - - [04/May/2024 20:55:38] "POST /analyze HTTP/1.1" 500 -
</code>
<code>The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable 127.0.0.1 - - [04/May/2024 20:55:38] "POST /analyze HTTP/1.1" 500 - </code>
The api_key client option must be set either by passing api_key to the client or by setting the OPENAI_API_KEY environment variable

127.0.0.1 - - [04/May/2024 20:55:38] "POST /analyze HTTP/1.1" 500 -

Could someone please help me here?

I have tried what was given by some on SO. But it just does not work.

3

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>from flask import Flask, request, jsonify, send_from_directory
import openai
from openai import OpenAI
import os
app = Flask(__name__)
@app.route('/')
def index():
return send_from_directory('.', 'index.html')
@app.route('/analyze', methods=['POST'])
def analyze_cv():
if 'cv' not in request.files or 'job_description' not in request.files:
return jsonify({'error': 'CV and Job Description files are required'}), 400
cv = request.files['cv'].read()
job_description = request.files['job_description'].read()
try:
cv = cv.decode('utf-8')
except UnicodeDecodeError:
cv = cv.decode('latin-1')
try:
job_description = job_description.decode('utf-8')
except UnicodeDecodeError:
job_description = job_description.decode('latin-1')
prompt = f"Given the following job description:n{job_description}nnAssess the suitability of the candidate based on the CV:n{cv}nnScore the candidate from 1 to 10 and provide an explanation."
try:
client = OpenAI(api_key='sk-')
response = client.completions.create(
model="gpt-3.5-turbo-instruct",
prompt=prompt,
temperature=0.7,
max_tokens=1024
)
score = int(response.choices[0].text.split()[0])
explanation = response.choices[0].text.split('n')[1]
return jsonify({'score': score, 'explanation': explanation}), 200
except Exception as e:
print(e)
return jsonify({'error': 'An error occurred while analyzing the CV'}), 500
if __name__ == '__main__':
app.run(debug=True)
</code>
<code>from flask import Flask, request, jsonify, send_from_directory import openai from openai import OpenAI import os app = Flask(__name__) @app.route('/') def index(): return send_from_directory('.', 'index.html') @app.route('/analyze', methods=['POST']) def analyze_cv(): if 'cv' not in request.files or 'job_description' not in request.files: return jsonify({'error': 'CV and Job Description files are required'}), 400 cv = request.files['cv'].read() job_description = request.files['job_description'].read() try: cv = cv.decode('utf-8') except UnicodeDecodeError: cv = cv.decode('latin-1') try: job_description = job_description.decode('utf-8') except UnicodeDecodeError: job_description = job_description.decode('latin-1') prompt = f"Given the following job description:n{job_description}nnAssess the suitability of the candidate based on the CV:n{cv}nnScore the candidate from 1 to 10 and provide an explanation." try: client = OpenAI(api_key='sk-') response = client.completions.create( model="gpt-3.5-turbo-instruct", prompt=prompt, temperature=0.7, max_tokens=1024 ) score = int(response.choices[0].text.split()[0]) explanation = response.choices[0].text.split('n')[1] return jsonify({'score': score, 'explanation': explanation}), 200 except Exception as e: print(e) return jsonify({'error': 'An error occurred while analyzing the CV'}), 500 if __name__ == '__main__': app.run(debug=True) </code>
from flask import Flask, request, jsonify, send_from_directory
import openai
from openai import OpenAI
import os

app = Flask(__name__)

@app.route('/')
def index():
    return send_from_directory('.', 'index.html')

@app.route('/analyze', methods=['POST'])
def analyze_cv():
    if 'cv' not in request.files or 'job_description' not in request.files:
        return jsonify({'error': 'CV and Job Description files are required'}), 400

    cv = request.files['cv'].read()
    job_description = request.files['job_description'].read()

    try:
        cv = cv.decode('utf-8')
    except UnicodeDecodeError:
        cv = cv.decode('latin-1')

    try:
        job_description = job_description.decode('utf-8')
    except UnicodeDecodeError:
        job_description = job_description.decode('latin-1')

    prompt = f"Given the following job description:n{job_description}nnAssess the suitability of the candidate based on the CV:n{cv}nnScore the candidate from 1 to 10 and provide an explanation."

    try:
        client = OpenAI(api_key='sk-')
        response = client.completions.create(
            model="gpt-3.5-turbo-instruct",
            prompt=prompt,
            temperature=0.7,
            max_tokens=1024
        )

        score = int(response.choices[0].text.split()[0])
        explanation = response.choices[0].text.split('n')[1]

        return jsonify({'score': score, 'explanation': explanation}), 200
    
    except Exception as e:
        print(e)  
        return jsonify({'error': 'An error occurred while analyzing the CV'}), 500

if __name__ == '__main__':
    app.run(debug=True)

This code now works. But another error pops up
127.0.0.1 – – [04/May/2024 22:29:55] “GET / HTTP/1.1” 304 –
Error code: 429 – {‘error’: {‘message’: ‘You exceeded your current quota, please check your plan and billing details. For more information on this error, read the docs: https://platform.openai.com/docs/guides/error-codes/api-errors.’, ‘type’: ‘insufficient_quota’, ‘param’: None, ‘code’: ‘insufficient_quota’}}
127.0.0.1 – – [04/May/2024 22:30:17] “POST /analyze HTTP/1.1” 500 –

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật