RuntimeError: Already borrowed

本文记录了一个关于SBERT模型接口部署后出现的RuntimeError:Alreadyborrowed错误。该错误发生于多线程环境下使用同一tokenizer时,解决方案包括采用TFRecord进行数据转换并通过文件流读取,最终采取了对批量数据进行切分的方法。

问题:

之前写的SBERT模型接口部署上线后最近报了RuntimeError: Already borrowed的错误,在这里记录下。

现象:

具体的报错如下:

  File "/home/XXXX/XXX/src/sentence_proc.py", line 77, in compute_sentence_vectors
    sentences = self.tokenizer(sentences, padding='max_length', truncation=True, max_length=self.max_seq_length,return_tensors="tf")
  File "/home/XXX/.local/lib/python3.8/site-packages/transformers/tokenization_utils_base.py", line 2249, in __call__
    return self.batch_encode_plus(
  File "/home/XXXX/.local/lib/python3.8/site-packages/transformers/tokenization_utils_base.py", line 2434, in batch_encode_plus
    return self._batch_encode_plus(
  File "/home/XXXX/.local/lib/python3.8/site-packages/transformers/tokenization_utils_fast.py", line 370, in _batch_encode_plus
    self.set_truncation_and_padding(
  File "/home/XXXX/.local/lib/python3.8/site-packages/transformers/tokenization_utils

Thanks to your work so far, the library now has a functioning system. However, librarians have reported that some records in the CSV files are corrupted with invalid values. This has caused misbehaviour in the system, sometimes even crashing during busy exam periods, creating unnecessary stress for students. In real-world software engineering, robustness and correctness are just as important as functionality. Programs must gracefully handle unexpected situations and invalid inputs without failing. Two key approaches developers use are: Assertions: Internal checks that validate assumptions made by the programmer (e.g., "This variable should never be negative"). Assertions are mainly used during development and debugging. Defensive programming: Validates inputs and usage patterns to prevent invalid or unexpected behaviour at runtime. This includes checking for correct types, value ranges, and providing helpful error messages when something goes wrong. Description In this task, you will extend your library system by adding custom error handling to make it more robust. Python already raises built-in errors, but here you must define and use custom exceptions (in custom_errors.py) to handle library-specific error conditions. Building upon Task 3, update your user.py and book.py modules to handle invalid input, and modify task4.py to handle exceptions gracefully so that the system does not crash. You must ensure that this system is: Correct: Through use of assert to validate assumptions in your logic. Safe: Through defensive programming techniques that prevent invalid inputs (e.g. wrong types, negative amounts). In this task we will be using custom errors as python will already raise some of these errors when we execute invalid code. Our new errors are located in cusom_errors.py. You must use these custom errors, please see rubric for related penalties in this task. After auditing the CSV data, the librarian has introduced new validation rules to be applied in addition to the requirements described in Tasks 1–3. These rules strengthen data quality and prevent corrupted records from entering the system. Always include a helpful and descriptive error message when raising errors. Doing so contributes to the readability and overall quality of your assignment. Users Every user must have a password. Passwords cannot be empty. Every word in a user's name must contain only alphabetic characters. Numbers, symbols, and special characters are not allowed. Department is mandatory for students and staff, but must remain empty for other users. The only valid departments are: IT, Business, Arts, Science, Engineering, Education, Medicine and Library. Books The library only recognizes two valid book types: physical and online. The following fields are required for all books: Title, Author, Year Each book may have at most 5 keywords. Each word in keywords must consist of letters and numbers only. The only allowed special character is the hyphen (-). Loans Every loan record must be associated with an existing user and an existing book. The due date is a required field and cannot be left empty. Defensive Programming The following exceptions are provided to you in custom_errors.py: CustomTypeError: A value is the wrong type (e.g. a string instead of a float or int). CustomValueError: A value is of the correct type but invalid (e.g. negative copies). CustomDateError: Raised when a date is in the wrong format or when the date logic is invalid (e.g., borrow date occurs in the future). MissingRequiredFieldError: Raised when a required field is missing. UserNotFoundError or BookNotFoundError: Raised when a loan references a user or book that does not exist. CustomOperationError : Raised when an invalid borrow or return action is attempted. CustomLimitError: Raised when a user exceeds their quota or borrowing limit. CustomKeyError: Occurs when you try to access a key in the dictionary that doesn't exist.
10-18
from xmlrpc.client import Boolean class Borrower: """Represents a person that can borrow books""" newIdCode = 1 # Class variable def __init__(self, firstname, lastname): self.firstname = firstname self.lastname = lastname self.id = Borrower.newIdCode Borrower.newIdCode += 1 # Updates for next new borrower ... self.booksBorrowed = [] def borrowBook(self, book): self.booksBorrowed.append(book) if Book.__init__.OnLoan: print("该书已经被借走了") def showAllBooks(self): for i in range(len(self.booksBorrowed)): print(self.firstname,self.lastname,"已经借走了",booksBorrowed[i]) def showBorrowerDetails(self): print(self.firstname, self.lastname, self.id) class Book: """A class to represent a book in a library""" def __init__(self, title, author, code): self.title = title self.author = author self.code = code OnLoan = False def showTitle(self): print(self.title) class Library: """A class to represent a lending library""" def __init__(self): self.allBorrowers = [] self.allBooks =[] def addBook(self, book): self.allBooks.append(book) def addBorrower(self, borrower): self.allBorrowers.append(borrower) def lendBook(self,borrower,book): if borrower in self.allBorrowers: print(borrower.firstname, borrower.lastname,end=" ") self.allBorrowers.remove(borrower) if book in self.allBooks: print("借走了",book.title) self.allBooks.remove(book) Book.__init__.OnLoan = True def main(): ## Create some books ... book1 = Book('Kafkas motorbike','Bridget Jones', 1290) book2 = Book('Cooking with Custard','Jello Biafra', 1002) book3 = Book('History of Bagpipes','John Cairncross', 987) # Put the books in the library library = Library() # Creates the library library.addBook(book1) library.addBook(book2) library.addBook(book3) # Create some borrowers ... bor1 = Borrower('Kevin','Wilson') bor2 = Borrower('Rita','Shapiro') bor3 = Borrower('Max','Normal') library.addBorrower(bor1) library.addBorrower(bor2) library.addBorrower(bor3) # make some loans ... library.lendBook(bor1, book1) bor1.showBorrowerDetails() bor1.showAllBooks() library.lendBook(bor2,book3) bor2.showBorrowerDetails() bor2.showAllBooks() # Try to lend book3 out again .... library.lendBook(bor3,book3) if __name__ == "__main__": main()
最新发布
10-28
评论 2
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值