99 save_credentials_to_config ,
1010 load_credentials_from_config ,
1111)
12-
12+ import leetcode
13+ import leetcode .auth
1314import requests
1415
1516
@@ -62,13 +63,13 @@ def execute_graphql_query(api_instance, data):
6263 headers = {
6364 "Content-Type" : "application/json" ,
6465 "Cookie" : f"csrftoken={ csrf_token } ; LEETCODE_SESSION={ leetcode_session } " ,
65- "Referer" : "https://leetcode.com"
66+ "Referer" : "https://leetcode.com" ,
6667 }
6768
6869 data = {
6970 "operationName" : data .get ("operationName" ),
7071 "query" : data .get ("query" ),
71- "variables" : data .get ("variables" )
72+ "variables" : data .get ("variables" ),
7273 }
7374
7475 response = requests .post (api_url , json = data , headers = headers )
@@ -132,18 +133,22 @@ def get_question_data_by_id(api_instance, q):
132133 "categorySlug" : "" ,
133134 "skip" : skip ,
134135 "limit" : limit ,
135- "filters" : filters
136+ "filters" : filters ,
136137 }
137138
138139 data = {
139140 "operationName" : "problemsetQuestionList" ,
140141 "query" : query ,
141- "variables" : query_variables
142+ "variables" : query_variables ,
142143 }
143144
144145 api_response = execute_graphql_query (api_instance , data )
145146
146- if api_response and "data" in api_response and "problemsetQuestionList" in api_response ["data" ]:
147+ if (
148+ api_response
149+ and "data" in api_response
150+ and "problemsetQuestionList" in api_response ["data" ]
151+ ):
147152 return api_response ["data" ]["problemsetQuestionList" ]["questions" ]
148153 return None
149154
@@ -217,7 +222,7 @@ def get_question_detail(api_instance, title_slug):
217222 data = {
218223 "operationName" : "getQuestionDetail" ,
219224 "query" : query ,
220- "variables" : query_variables
225+ "variables" : query_variables ,
221226 }
222227
223228 api_response = execute_graphql_query (api_instance , data )
@@ -228,40 +233,49 @@ def get_question_detail(api_instance, title_slug):
228233
229234
230235LANG_EXTENSIONS = {
231- ' cpp' : ' cpp' ,
232- ' java' : ' java' ,
233- ' python' : 'py' ,
234- ' python3' : 'py' ,
235- 'c' : 'c' ,
236- ' csharp' : 'cs' ,
237- ' javascript' : 'js' ,
238- ' ruby' : 'rb' ,
239- ' swift' : ' swift' ,
240- ' golang' : 'go' ,
241- ' scala' : ' scala' ,
242- ' kotlin' : 'kt' ,
243- ' rust' : 'rs' ,
244- ' php' : ' php' ,
245- ' typescript' : 'ts' ,
246- ' racket' : ' rkt' ,
247- ' erlang' : ' erl' ,
248- ' elixir' : 'ex' ,
249- ' dart' : ' dart'
236+ " cpp" : " cpp" ,
237+ " java" : " java" ,
238+ " python" : "py" ,
239+ " python3" : "py" ,
240+ "c" : "c" ,
241+ " csharp" : "cs" ,
242+ " javascript" : "js" ,
243+ " ruby" : "rb" ,
244+ " swift" : " swift" ,
245+ " golang" : "go" ,
246+ " scala" : " scala" ,
247+ " kotlin" : "kt" ,
248+ " rust" : "rs" ,
249+ " php" : " php" ,
250+ " typescript" : "ts" ,
251+ " racket" : " rkt" ,
252+ " erlang" : " erl" ,
253+ " elixir" : "ex" ,
254+ " dart" : " dart" ,
250255}
251256
252257
253258def get_code_snippets (question_detail_data , lang_slug ):
254259 code_snippets = question_detail_data .get ("codeSnippets" , [])
255- return next ((snippet ['code' ] for snippet in code_snippets if snippet ['langSlug' ] == lang_slug ), None )
260+ return next (
261+ (
262+ snippet ["code" ]
263+ for snippet in code_snippets
264+ if snippet ["langSlug" ] == lang_slug
265+ ),
266+ None ,
267+ )
256268
257269
258270def write_code_snippet_to_file (question_detail_data , lang , title_slug ):
259271 code = get_code_snippets (question_detail_data , lang )
260272 if code :
261273 lang_extension = LANG_EXTENSIONS .get (lang )
262274 if lang_extension :
263- file_path = os .path .join ("code_editor" ,
264- f"{ question_detail_data ['questionFrontendId' ]} _{ title_slug } .{ lang_extension } " )
275+ file_path = os .path .join (
276+ "code_editor" ,
277+ f"{ question_detail_data ['questionFrontendId' ]} _{ title_slug } .{ lang_extension } " ,
278+ )
265279 with open (file_path , "w" ) as file :
266280 file .write (code )
267281 print (f"Code snippet for { lang } has been written to { file_path } ." )
@@ -272,12 +286,12 @@ def write_code_snippet_to_file(question_detail_data, lang, title_slug):
272286
273287
274288def display_available_languages (question_detail_data ):
275- code_snippets = question_detail_data .get (' codeSnippets' , [])
289+ code_snippets = question_detail_data .get (" codeSnippets" , [])
276290 if code_snippets :
277291 print ("Available Languages:" )
278292 for index , snippet in enumerate (code_snippets ):
279- lang_slug = snippet .get (' langSlug' )
280- lang_name = snippet .get (' text' ) or lang_slug
293+ lang_slug = snippet .get (" langSlug" )
294+ lang_name = snippet .get (" text" ) or lang_slug
281295 print (f"{ index + 1 } . { lang_name } ({ lang_slug } )" )
282296 else :
283297 print ("No code snippets available." )
@@ -295,19 +309,25 @@ def display_question_detail(api_instance, title_slug):
295309
296310 display_available_languages (question_detail_data )
297311
298- lang_input = input ("Enter the index of the language you want to code: " ).strip ().lower ()
312+ lang_input = (
313+ input ("Enter the index of the language you want to code: " ).strip ().lower ()
314+ )
299315 try :
300316 lang_index = int (lang_input )
301- if 1 <= lang_index <= len (question_detail_data .get ('codeSnippets' , [])):
302- selected_lang = question_detail_data ['codeSnippets' ][lang_index - 1 ]['langSlug' ]
303- write_code_snippet_to_file (question_detail_data , selected_lang , title_slug )
317+ if 1 <= lang_index <= len (question_detail_data .get ("codeSnippets" , [])):
318+ selected_lang = question_detail_data ["codeSnippets" ][lang_index - 1 ][
319+ "langSlug"
320+ ]
321+ write_code_snippet_to_file (
322+ question_detail_data , selected_lang , title_slug
323+ )
304324 else :
305325 print ("Invalid index. Please enter a valid index." )
306326 except ValueError :
307327 print ("Invalid input. Please enter a valid index." )
308328
309329
310- def configuration ():
330+ def configuratio (): #had to change name becasue of python-leetcode lib
311331 leetcode_session , csrf_token = load_credentials_from_config ()
312332 if not leetcode_session or not csrf_token :
313333 leetcode_session = click .prompt ("Enter your LeetCode session" , type = str )
@@ -319,37 +339,38 @@ def configuration():
319339def get_title_slug_from_filename (filepath ):
320340 base_name = os .path .basename (filepath )
321341 title_slug , _ = os .path .splitext (base_name )
322- parts = title_slug .split ('_' )
342+ parts = title_slug .split ("_" )
323343 return "_" .join (parts [1 :])
324344
325345
326- def interpret_solution (api_instance , title_slug , payload ):
327- csrf_token , leetcode_session = api_instance
346+ def interpret_solution (title_slug , payload , api_instance ):
347+ test_submission = leetcode .TestSubmission (
348+ data_input = payload ["data_input" ],
349+ typed_code = payload ["typed_code" ],
350+ question_id = payload ["question_id" ],
351+ test_mode = False ,
352+ lang = "python3" ,
353+ )
354+ interpretation_id = api_instance .problems_problem_interpret_solution_post (
355+ problem = title_slug , body = test_submission
356+ )
328357
329- api_url = f"https://leetcode.com/problems/{ title_slug } /interpret_solution/"
358+ print ("Test has been queued. Result:" )
359+ print (interpretation_id )
330360
331- headers = {
332- "User-Agent" : "curl/8.0.1" ,
333- "Host" : "leetcode.com" ,
334- "Accept" : "*/*" ,
335- "content-type" : "application/json" ,
336- "Origin" : "https://leetcode.com" ,
337- "Content-Type" : "application/json" ,
338- "Referer" : f"https://leetcode.com/problems/{ title_slug } /" ,
339- "x-csrftoken" : csrf_token ,
340- "Cookie" : f"LEETCODE_SESSION={ leetcode_session } ;csrftoken={ csrf_token } ;"
341- }
342361
343- response = requests .post (api_url , json = payload , headers = headers )
362+ def initialize_leetcode_api_instance (leetcode_session ):
363+ configuration = leetcode .Configuration ()
364+ csrf_token = leetcode .auth .get_csrf_cookie (leetcode_session )
344365
345- time .sleep (10 )
366+ configuration .api_key ["x-csrftoken" ] = csrf_token
367+ configuration .api_key ["csrftoken" ] = csrf_token
368+ configuration .api_key ["LEETCODE_SESSION" ] = leetcode_session
369+ configuration .api_key ["Referer" ] = "https://leetcode.com"
370+ configuration .debug = False
346371
347- if response .status_code == 200 :
348- return response .json ()
349- else :
350- print (f"Interpret solution request failed with status code { response .status_code } :" )
351- print (response .text )
352- return None
372+ api_instance = leetcode .DefaultApi (leetcode .ApiClient (configuration ))
373+ return api_instance
353374
354375
355376@click .command ()
@@ -361,13 +382,23 @@ def interpret_solution(api_instance, title_slug, payload):
361382 default = "" ,
362383 help = "Specify the question ID, title, or range (e.g., 10:20)" ,
363384)
364- @click .option ("--solve" , "-s" , type = str , default = "" ,
365- help = "Specify the question title slug to solve (e.g., add-two-numbers)" )
366- @click .option ("--test" , "-t" , type = str , default = "" ,
367- help = "Specify the filename containing the code and input for testing" )
385+ @click .option (
386+ "--solve" ,
387+ "-s" ,
388+ type = str ,
389+ default = "" ,
390+ help = "Specify the question title slug to solve (e.g., add-two-numbers)" ,
391+ )
392+ @click .option (
393+ "--test" ,
394+ "-t" ,
395+ type = str ,
396+ default = "" ,
397+ help = "Specify the filename containing the code and input for testing" ,
398+ )
368399def main (config , question , solve , test ):
369400 if config :
370- leetcode_session , csrf_token = configuration ()
401+ leetcode_session , csrf_token = configuratio ()
371402 else :
372403 leetcode_session , csrf_token = load_credentials_from_config ()
373404
@@ -379,12 +410,17 @@ def main(config, question, solve, test):
379410 elif question :
380411 question_data = get_question_data_by_id (api_instance , question )
381412 if question_data :
382- sorted_question_data = sorted (question_data , key = lambda x : int (x ["frontendQuestionId" ]))
413+ sorted_question_data = sorted (
414+ question_data , key = lambda x : int (x ["frontendQuestionId" ])
415+ )
383416 for question_item in sorted_question_data :
384417 print_question_data (question_item )
385418 else :
386419 print (f"Question with ID or title '{ question } ' not found." )
387420 elif test :
421+ leetcode_api_instance = initialize_leetcode_api_instance (
422+ leetcode_session
423+ ) # here using python-leetcode
388424 print (f"Test file: { test } " )
389425 title_slug = get_title_slug_from_filename (test )
390426 print (f"Title slug: { title_slug } " )
@@ -402,18 +438,10 @@ def main(config, question, solve, test):
402438 "lang" : "python3" ,
403439 "question_id" : question_id ,
404440 "typed_code" : code ,
405- "data_input" : sample_test_case
441+ "data_input" : sample_test_case ,
406442 }
407443
408- json_payload = json .dumps (payload , indent = 4 ) # Convert payload to JSON string
409- print (json_payload )
410-
411- result = interpret_solution (api_instance , title_slug , json_payload )
412- if result and "interpret_id" in result :
413- interpret_id = result ["interpret_id" ]
414- print (f"Interpret ID: { interpret_id } " )
415- else :
416- print ("Interpret solution failed." )
444+ interpret_solution (title_slug , payload , leetcode_api_instance ) # used here
417445 else :
418446 print (f"Question with title slug '{ title_slug } ' not found." )
419447
0 commit comments