Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added API endpoints for Future Frontend development #5

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 41 additions & 20 deletions analyzer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,34 @@

#TODO: update PROBLEMS declaration to match project

PROBLEMS = {
"hog":{
"roll_dice": ["def roll_dice", "def free_bacon"],
"play": ["def play", "#######################"],
"max_scoring_num_rolls": ["def max_scoring_num_rolls", "def winner"]},
"typing":{
"accuracy": ["def accuracy", "def wpm"],
"autocorrect": ["def autocorrect", "def swap_diff"]
},
"ants":{
"Short and LongThrowers": ["class ShortThrower", "class FireAnt"],
"ThrowerAnt": ["class ThrowerAnt", "def throw_at"],
"FireAnt": ["class FireAnt", "class HungryAnt"],
"BodyguardAnt - Ant": ["class BodyguardAnt", "class TankAnt"],
"BodyguardAnt - Place": ["def add_insect", "def remove_insect"],
}
}

# PROBLEMS = {
# "roll_dice": ["def roll_dice", "def free_bacon"],
# "play": ["def play", "#######################"],
# "max_scoring_num_rolls": ["def max_scoring_num_rolls", "def winner"],
# }

PROBLEMS = {
"accuracy": ["def accuracy", "def wpm"],
"autocorrect": ["def autocorrect", "def sphinx_swap"],
}
# PROBLEMS = {
# "accuracy": ["def accuracy", "def wpm"],
# "autocorrect": ["def autocorrect", "def sphinx_swap"],
# }


# PROBLEMS = {
Expand Down Expand Up @@ -61,34 +79,37 @@ def comments(self) -> Generator[Comment, None, None]:
TARGETED_CHECKERS: Dict[str, List[Type[Checker]]] = {}


def get_problems(code: str):
def get_problems(code,problem_name="hog"):
out = {}
for name, (start, end) in PROBLEMS.items():
for name, (start, end) in PROBLEMS[problem_name].items():
start_index = code.index(start)
end_index = code.index(end)
initial_line_number = code[:start_index].count("\n") + 1
func_code = code[start_index:end_index].strip()

comments = []

tree = ast.parse(func_code)
for checker in CHECKERS + TARGETED_CHECKERS.get(name, []):
checker = checker(func_code)
checker.visit(tree)
for comment in checker.comments():
comments.append(
Comment(
comment.line_num + initial_line_number - 1,
comment.comment,
comment.fields,
)
)
comments=check_problem(func_code,name)

comments.sort(key=lambda x: x.line_num)

out[name] = Problem(func_code, initial_line_number, comments)
return out

def check_problem(func_code,name,initial_line_number=0):
comments = []

tree = ast.parse(func_code)
for checker in CHECKERS + TARGETED_CHECKERS.get(name, []):
checker = checker(func_code)
checker.visit(tree)
for comment in checker.comments():
comments.append(
Comment(
comment.line_num + initial_line_number - 1,
comment.comment,
comment.fields,
)
)
return comments

# @checker
class VariableNotNeededChecker(Checker):
Expand Down
81 changes: 81 additions & 0 deletions manage.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
from flask import Flask, request, jsonify
from flask_script import Manager
from analyzer import get_problems, Comment, PROBLEMS,check_problem
from finalizing import grade as f_grade
from ok_interface import get_backup_ids as f_get_backup_ids, submit_comment
import requests
import auth
from ok_interface import ACCESS_TOKEN

app = Flask(__name__)
manager = Manager(app)

HTTPEXCEPTIONS = {
1:"BAD REQUEST:No 'code' field",
2:"BAD REQUEST:Code Execution Error",
3: "BAD REQUEST:No 'comment' field",
4:"BAD REQUEST: Illegal Files"
}

def illegal_request(id):
return HTTPEXCEPTIONS.get(id),400

@app.route('/api/get_backup_ids', methods=['GET'])
def get_backup_ids():
id = request.args.get('id',default = -1, type = int)
print ("THIS is: ",id)
return "x"

@app.route('/api/get_backup_problems', methods=['GET'])
def get_backup_problems():
id = request.args.get('id', default="", type=str)
print ("THIS is: ", id)
params = {"access_token": ACCESS_TOKEN}
r = requests.get(f"https://okpy.org/api/v3/backups/{id}", params=params)
messages = r.json()["data"]["messages"][0]
out = []
print("MESSEGSES:", messages)
for proj_name in PROBLEMS:
print(proj_name+".py")
if proj_name+".py" in messages["contents"]:
problems = PROBLEMS[proj_name]
project = proj_name
code = messages["contents"][proj_name+".py"]
break
else:
return illegal_request(4)
for name, (start, end) in problems.items():
start_index = code.index(start)
end_index = code.index(end)
initial_line_number = code[:start_index].count("\n") + 1
func_code = code[start_index:end_index].strip()
out.append({"problem_name":name,"problem_body":func_code,"initial_line_number":initial_line_number})

return jsonify(out)

@app.route('/get_potential_comments', methods=['POST'])
def get_comment():
try:
code = request.json.get("problem_body")
problem = request.json.get("problem_name")
init_line = request.json.get("initial_line_number")
except:
return illegal_request(1)
result = check_problem(code,problem,init_line)
return jsonify(result)

@app.route('/submit_comment/', methods=['POST'])
def grade():
try:
id = request.json.get("id")
comments = request.json.get("comments")
except:
return illegal_request(3)
result = f_grade(comments)
for comment in comments:
submit_comment(id,comment["line_num"],comment["comment"])
return jsonify(result)


if __name__ == "__main__":
manager.run()
2 changes: 1 addition & 1 deletion ok_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ def get_backup_ids(file="raw_queue.txt", completed_file="completed"):

Keyword arguments:
file -- the file path to the list of submission URLs (default "raw_queue.txt")
This file can just contain the HTML source code of the grading queue on OKpy.
This file can just contain the HTML source code of the grading queue on OKpy.
The links will be automatically extracted and the file updated.
completed_file -- the file path to the list of completed submission IDs (default "completed")
"""
Expand Down