Compare commits

..

5 Commits

8 changed files with 285 additions and 15 deletions

View File

@ -18,7 +18,7 @@ picked from articles selected for him to read according his vocabulary level. E
`python3 main.py`
Make sure you have put the SQLite database file in the path `app/db` (see below).
Make sure you have put the SQLite database file in the path `app/static` (see below).
## Run it as a Docker container
@ -214,5 +214,5 @@ Bug report: http://118.25.96.118/bugzilla/show_bug.cgi?id=215
Bug report: http://118.25.96.118/bugzilla/show_bug.cgi?id=489
*Last modified on 2026-03-12*
*Last modified on 2023-01-30*

View File

@ -84,7 +84,7 @@ def get_today_article(user_word_list, visited_articles):
text_level = 0
if visited_articles["index"] > len(visited_articles["article_ids"]) - 1: # 生成新的文章
amount_of_visited_articles = len(visited_articles["article_ids"])
amount_of_existing_articles = result.__len__()
amount_of_existing_articles = len(result)
if amount_of_visited_articles == amount_of_existing_articles: # 如果当前阅读过的文章的数量 == 存在的文章的数量,即所有的书本都阅读过了
result_of_generate_article = "had read all articles"
else:
@ -106,8 +106,20 @@ def get_today_article(user_word_list, visited_articles):
text_level = text_difficulty_level(d['text'], d3)
result_of_generate_article = "found"
today_article = {}
if d:
if d is None:
# 如果没有找到合适的文章,返回一个默认的文章对象
today_article = {
"user_level": '0.0',
"text_level": '0.0',
"date": datetime.now().strftime('%Y-%m-%d'),
"article_title": "Default Article",
"article_body": "This is a default article for testing purposes.",
"source": "Default Source",
"question": "What is this article about?",
"answer": "It's a default article for testing.Please contact the administrator",
"ratio": 0.0
}
else:
oxford_words = load_oxford_words(oxford_words_path)
oxford_word_count, total_words = count_oxford_words(d['text'], oxford_words)
ratio = calculate_ratio(oxford_word_count, total_words)

View File

@ -144,8 +144,8 @@ if __name__ == '__main__':
运行程序
'''
# app.secret_key = os.urandom(16)
app.run(debug=True, port=5000)
# app.run(debug=True)
# app.run(debug=False, port='6000')
app.run(debug=True)
# app.run(debug=True, port='6000')
# app.run(host='0.0.0.0', debug=True, port='6000')
# print(mod5('123'))

View File

@ -31,7 +31,7 @@
<p><a href="/login">登录</a> <a href="/signup">注册</a> <a href="/static/usr/instructions.html">使用说明</a></p >
<p><b> {{ random_ads }}。 <a href="/signup">试试</a>吧!</b></p>
{% endif %}
<div class="alert alert-success" role="alert">共有文章 <span class="badge bg-success"> {{ number_of_essays }} </span> 篇,Oxford 5000 单词占比 <span class="badge bg-success"> {{ (ratio * 100) | int }}% </span> </div>
<div class="alert alert-success" role="alert">共有文章 <span class="badge bg-success"> {{ number_of_essays }} </span> 篇,覆盖 <span class="badge bg-success"> {{ (ratio * 100) | int }}% </span> 的 Oxford5000 单词</div>
<p>粘贴1篇文章 (English only)</p>
<form method="post" action="/">
<textarea name="content" id="article" rows="10" cols="120"></textarea><br/>

View File

@ -87,7 +87,7 @@
<div id="text-content">
<div id="found">
<div class="alert alert-success" role="alert">According to your word list, your level is <span class="text-decoration-underline" id="user_level">{{ today_article["user_level"] }}</span> and we have chosen an article with a difficulty level of <span class="text-decoration-underline" id="text_level">{{ today_article["text_level"] }}</span> for you. <span class="text-decoration-underline" id="ratio">{{ (today_article["ratio"] * 100) | int }}%</span> of the words in this article are in Oxford Word 5000.</div>
<div class="alert alert-success" role="alert">According to your word list, your level is <span class="text-decoration-underline" id="user_level">{{ today_article["user_level"] }}</span> and we have chosen an article with a difficulty level of <span class="text-decoration-underline" id="text_level">{{ today_article["text_level"] }}</span> for you. The Oxford word coverage is <span class="text-decoration-underline" id="ratio">{{ (today_article["ratio"] * 100) | int }}%.</span></div>
<p class="text-muted" id="date">Article added on: {{ today_article["date"] }}</p><br/>
<button onclick="saveArticle()" >标记文章</button>

BIN
app/test/article_test.p Normal file

Binary file not shown.

94
app/test_vocabulary.py Normal file
View File

@ -0,0 +1,94 @@
# Run this test script on the command line:
# pytest test_vocabulary.py
#
# Last modified by Mr Lan Hui on 2025-03-05
from vocabulary import UserVocabularyLevel, ArticleVocabularyLevel
def test_article_level_empty_content():
''' Boundary case test '''
article = ArticleVocabularyLevel('')
assert article.level == 0
def test_article_level_punctuation_only():
''' Boundary case test '''
article = ArticleVocabularyLevel(',')
assert article.level == 0
def test_article_level_digit_only():
''' Boundary case test '''
article = ArticleVocabularyLevel('1')
assert article.level == 0
def test_article_level_single_word():
''' Boundary case test '''
article = ArticleVocabularyLevel('source')
assert 2 <= article.level <= 4
def test_article_level_subset_vs_superset():
''' Boundary case test '''
article1 = ArticleVocabularyLevel('source')
article2 = ArticleVocabularyLevel('open source')
assert article1.level < article2.level
def test_article_level_multiple_words():
''' Boundary case test '''
article = ArticleVocabularyLevel('Producing Open Source Software - How to Run a Successful Free Software Project')
assert 3 <= article.level <= 5
def test_article_level_short_paragraph():
''' Boundary case test '''
article = ArticleVocabularyLevel('At parties, people no longer give me a blank stare when I tell them I work in open source software. "Oh, yes — like Linux?" they say. I nod eagerly in agreement. "Yes, exactly! That\'s what I do." It\'s nice not to be completely fringe anymore. In the past, the next question was usually fairly predictable: "How do you make money doing that?" To answer, I\'d summarize the economics of free software: that there are organizations in whose interest it is to have certain software exist, but that they don\'t need to sell copies, they just want to make sure the software is available and maintained, as a tool instead of as a rentable monopoly.')
assert 4 <= article.level <= 6
def test_article_level_medium_paragraph():
''' Boundary case test '''
article = ArticleVocabularyLevel('In considering the Origin of Species, it is quite conceivable that a naturalist, reflecting on the mutual affinities of organic beings, on their embryological relations, their geographical distribution, geological succession, and other such facts, might come to the conclusion that each species had not been independently created, but had descended, like varieties, from other species. Nevertheless, such a conclusion, even if well founded, would be unsatisfactory, until it could be shown how the innumerable species inhabiting this world have been modified, so as to acquire that perfection of structure and coadaptation which most justly excites our admiration. Naturalists continually refer to external conditions, such as climate, food, etc., as the only possible cause of variation. In one very limited sense, as we shall hereafter see, this may be true; but it is preposterous to attribute to mere external conditions, the structure, for instance, of the woodpecker, with its feet, tail, beak, and tongue, so admirably adapted to catch insects under the bark of trees. In the case of the misseltoe, which draws its nourishment from certain trees, which has seeds that must be transported by certain birds, and which has flowers with separate sexes absolutely requiring the agency of certain insects to bring pollen from one flower to the other, it is equally preposterous to account for the structure of this parasite, with its relations to several distinct organic beings, by the effects of external conditions, or of habit, or of the volition of the plant itself.')
assert 5 <= article.level <= 7
def test_article_level_long_paragraph():
''' Boundary case test '''
article = ArticleVocabularyLevel('These several facts accord well with my theory. I believe in no fixed law of development, causing all the inhabitants of a country to change abruptly, or simultaneously, or to an equal degree. The process of modification must be extremely slow. The variability of each species is quite independent of that of all others. Whether such variability be taken advantage of by natural selection, and whether the variations be accumulated to a greater or lesser amount, thus causing a greater or lesser amount of modification in the varying species, depends on many complex contingencies,—on the variability being of a beneficial nature, on the power of intercrossing, on the rate of breeding, on the slowly changing physical conditions of the country, and more especially on the nature of the other inhabitants with which the varying species comes into competition. Hence it is by no means surprising that one species should retain the same identical form much longer than others; or, if changing, that it should change less. We see the same fact in geographical distribution; for instance, in the land-shells and coleopterous insects of Madeira having come to differ considerably from their nearest allies on the continent of Europe, whereas the marine shells and birds have remained unaltered. We can perhaps understand the apparently quicker rate of change in terrestrial and in more highly organised productions compared with marine and lower productions, by the more complex relations of the higher beings to their organic and inorganic conditions of life, as explained in a former chapter. When many of the inhabitants of a country have become modified and improved, we can understand, on the principle of competition, and on that of the many all-important relations of organism to organism, that any form which does not become in some degree modified and improved, will be liable to be exterminated. Hence we can see why all the species in the same region do at last, if we look to wide enough intervals of time, become modified; for those which do not change will become extinct.')
assert 6 <= article.level <= 8
def test_user_level_empty_dictionary():
''' Boundary case test '''
user = UserVocabularyLevel({})
assert user.level == 0
def test_user_level_one_simple_word():
''' Boundary case test '''
user = UserVocabularyLevel({'simple':['202408050930']})
assert 0 < user.level <= 4
def test_user_level_invalid_word():
''' Boundary case test '''
user = UserVocabularyLevel({'xyz':['202408050930']})
assert user.level == 0
def test_user_level_one_hard_word():
''' Boundary case test '''
user = UserVocabularyLevel({'pasture':['202408050930']})
assert 5 <= user.level <= 8
def test_user_level_multiple_words():
''' Boundary case test '''
user = UserVocabularyLevel(
{'sessile': ['202408050930'], 'putrid': ['202408050930'], 'prodigal': ['202408050930'], 'presumptuous': ['202408050930'], 'prehension': ['202408050930'], 'pied': ['202408050930'], 'pedunculated': ['202408050930'], 'pasture': ['202408050930'], 'parturition': ['202408050930'], 'ovigerous': ['202408050930'], 'ova': ['202408050930'], 'orifice': ['202408050930'], 'obliterate': ['202408050930'], 'niggard': ['202408050930'], 'neuter': ['202408050930'], 'locomotion': ['202408050930'], 'lineal': ['202408050930'], 'glottis': ['202408050930'], 'frivolous': ['202408050930'], 'frena': ['202408050930'], 'flotation': ['202408050930'], 'ductus': ['202408050930'], 'dorsal': ['202408050930'], 'dearth': ['202408050930'], 'crustacean': ['202408050930'], 'cornea': ['202408050930'], 'contrivance': ['202408050930'], 'collateral': ['202408050930'], 'cirriped': ['202408050930'], 'canon': ['202408050930'], 'branchiae': ['202408050930'], 'auditory': ['202408050930'], 'articulata': ['202408050930'], 'alimentary': ['202408050930'], 'adduce': ['202408050930'], 'aberration': ['202408050930']}
)
assert 6 <= user.level <= 8
def test_user_level_consider_only_most_recent_words_difficult_words_most_recent():
''' Consider only the most recent three words '''
user = UserVocabularyLevel(
{'pasture':['202408050930'], 'putrid': ['202408040000'], 'frivolous':['202408030000'], 'simple':['202408020000'], 'apple':['202408010000']}
)
assert 5 <= user.level <= 8
def test_user_level_consider_only_most_recent_words_easy_words_most_recent():
''' Consider only the most recent three words '''
user = UserVocabularyLevel(
{'simple':['202408050930'], 'apple': ['202408040000'], 'happy':['202408030000'], 'pasture':['202408020000'], 'putrid':['202408010000'], 'dearth':['202407310000']}
)
assert 4 <= user.level <= 5

164
app/vocabulary.py Normal file
View File

@ -0,0 +1,164 @@
import os
import pickle
import random
import re
from collections import defaultdict
from datetime import datetime, timedelta
import snowballstemmer
from flask import session
# 词汇表加载
def load_record(pickle_fname):
with open(pickle_fname, 'rb') as f:
d = pickle.load(f)
return d
# 判断是否是英文单词
def is_english_word(word):
pattern = re.compile(r'^[a-zA-Z]+$')
return bool(pattern.match(word))
# 去除非单词字符
def remove_non_words(input_string):
cleaned_string = re.sub(r'[^a-zA-Z\s]', '', input_string)
words = cleaned_string.split()
return ' '.join(words)
# 主类:词汇水平估算器
class VocabularyLevelEstimator:
# 词汇表(单词:【"雅思","高考"...】)
_test = load_record('static/words_and_tests.p') # 词汇到测试来源的映射
@property
def level(self):
total = 0.0
num = 0
for word in self.word_lst:
if word in self._test:
total += self._test[word] # Assuming _test[word] returns a difficulty score
num += 1
return total / num if num > 0 else 0.0
def get_word_level(self, word):
# 常见高频词汇列表
other = ['went', 'heard', 'i', 'feet', 'got', 'been', 'gone', 'done', 'had', 'said', 'seen', 'made',
'taken', 'come', 'gotten', 'got ', 'ran', 'eaten', 'written', 'found', 'given', 'told',
'brought', 'kept', 'stood', 'sat', 'won', 'bought', 'caught', 'begun', 'drank', 'rang', 'sang',
'swam', 'blew', 'drew', 'flew', 'grew', 'knew', 'threw', 'shown', 'broken', 'chosen', 'forgotten',
'spoke', 'woke', 'woken', 'driven', 'fell', 'given', 'risen', 'mistaken', 'ridden', 'lain', 'lied']
if word not in self._test: return 3 # 如果词汇不在测试数据中返回3级
if word in other: return 3 # 如果是常见的高频词汇返回3级
k = self._test[word]
# 根据词汇的来源设置等级
if 'CET4' in k:
return 4
elif 'OXFORD3000' in k:
return 5
elif 'CET6' in k or 'GRADUATE' in k:
return 6
elif 'OXFORD5000' in k or 'IELTS' in k:
return 7
elif 'BBC' in k:
return 8
# 用户词汇水平类
class UserVocabularyLevel(VocabularyLevelEstimator):
# 过滤后的用户生词库
filtered_frequency = []
def __init__(self, d):
if d:
self.d = d # 用户的生词库
self.word_lst = list(d.keys())
self.filter_user_frequency()
def filter_user_frequency(self):
stemmer = snowballstemmer.stemmer('english')
self.filtered_frequency = []
for word in self.d:
if is_english_word(word) :
if word not in self.filtered_frequency:
self.filtered_frequency.append(stemmer.stemWord(word))
@property
def level(self):
total = 0.0
num = 0
if not self.filtered_frequency: return 0.0
for word in self.filtered_frequency:
num += 1
total += self.get_word_level(word)
return total / num if num else 0.0
# 文章词汇难度类
class ArticleVocabularyLevel(VocabularyLevelEstimator):
difficulty_word = dict()
def __init__(self, content):
if content:
self.content = remove_non_words(content)
self.word_lst = self.content.lower().split()
self.select_difficulty_word()
def select_difficulty_word(self, n=10):
self.difficulty_word = {}
stemmer = snowballstemmer.stemmer('english')
for word in self.word_lst:
original_word = stemmer.stemWord(word)
self.difficulty_word[original_word] = self.get_word_level(original_word)
if self.difficulty_word:
sorted_words = sorted(self.difficulty_word.items(), key=lambda item: item[1], reverse=True)
top_words = sorted_words[:n]
self.difficulty_word = {word: difficulty for word, difficulty in top_words}
@property
def level(self):
total = 0.0
num = 0
if not self.difficulty_word: return 0.0
for word in self.difficulty_word:
num += 1
total += self.difficulty_word[word]
return total / num if num else 0.0
if __name__ == '__main__':
d = load_record('static/frequency/frequency_sb.pickle') # 加载用户词汇数据
print(d)
user = UserVocabularyLevel(d)
print('用户词汇水平:')
print(user.level) # 输出用户的词汇水平
s = """Energetic = haze dynamic = vigorous = animated Such is Love , Plain like Water
port him to stand up. She scolded him for not having waken her up. He said that he could manage. A serious quarrel was about to burst out again.
I called them from Zhuhai, the beautiful city of relaxation and exciting views. I wanted to depict to them how pretty a city Zhuhai is."""
article = ArticleVocabularyLevel(s)
print('文章词汇难度:')
print(article.level) # 输出文章的词汇难度
# 测试文章保存
with open('test/article_test.p', 'wb') as file:
pickle.dump(s, file)
with open('test/article_test.p', 'rb') as file:
loaded_data = pickle.load(file)
print(loaded_data)
article1 = ArticleVocabularyLevel('source')
article2 = ArticleVocabularyLevel('open source')