-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbully.py
62 lines (47 loc) · 1.46 KB
/
bully.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
from flask import Flask, request, jsonify
import requests as req
import os
import pdfplumber
# import os
from dotenv import load_dotenv
import ai21
# Load your API key from the .env file
load_dotenv()
app = Flask(__name__)
# Load your AI21 API key from the .env file
# API_KEY = os.environ.get('API_KEY')
API_KEY = os.getenv("AI21_API_KEY")
# Load context from a PDF or text file
def load_context(file_path):
if file_path.endswith(".pdf"):
with pdfplumber.open(file_path) as pdf:
context = ""
for page in pdf.pages:
context += page.extract_text()
return context
elif file_path.endswith((".txt", ".md")):
with open(file_path, "r") as file:
context = file.read()
return context
else:
return "Unsupported file format. Please use PDF, TXT, or MD."
# Initialize the context
CONTEXT_FILE = "workplacebullying.pdf" # Replace with your context file
context = load_context(CONTEXT_FILE)
@app.route("/")
def get_answer():
question = request.args.get('question')
url = "https://api.ai21.com/studio/v1/experimental/answer"
payload = {
"context": context,
"question": question
}
headers = {
"accept": "application/json",
"content-type": "application/json",
"Authorization": f'Bearer {API_KEY}'
}
response = req.post(url, json=payload, headers=headers)
return response.text
if __name__ == "__main__":
app.run()