Skip to content

Commit 322f27c

Browse files
Merge pull request #139 from gomate-community/pipeline
updtae@optimize chunks
2 parents 8a6256f + 0ebb256 commit 322f27c

File tree

11 files changed

+627
-242
lines changed

11 files changed

+627
-242
lines changed

data/docs/bbc新闻.txt

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
2025科技领域的趋势:加密货币与个人化AI
2+
一幅描绘特朗普手持比特币的卡通图片展示于香港的Coinhero商店内。图像来源,Getty Images
3+
图像加注文字,比特币的价格12月一度飙升至10万美元以上。
4+
2025年1月2日
5+
随着比特币在2024年突破10万美元大关,以及人工智能(AI)工具逐渐融入我们的口袋和手机,新的一年会有什么发展呢?
6+
7+
BBC商业科技编辑本·莫里斯(Ben Morris)与BBC科技编辑佐伊·克莱曼(Zoe Kleinman)带您探讨未来一年的顶尖趋势。
8+
9+
本·莫里斯(Ben Morris),BBC商业科技编辑
10+
11+
2022年尾声的时候,加密货币行业的前景一片黯淡。
12+
13+
其中一家最知名的公司FTX倒闭,造成80亿美元(约63亿英镑)客户资金不翼而飞。
14+
15+
2024年3月,该公司的联合创办人萨姆·班克曼-弗里德(Sam Bankman-Fried)因诈骗客户和投资者被判入狱25年。
16+
17+
这一丑闻动摇了整个行业的信心。
18+
19+
当时,加密货币似乎仍然是一种小众的产品,拥有一群热情但数量相对有限的支持者。
20+
21+
然而,仅仅几个月后,这个行业又重新充满乐观的情绪。这股热情背后的推动力来自特朗普在11月5日的美国总统选举中成功当选。
22+
23+
人们普遍认为,特朗普将对加密货币行业更加友好,而目前的迹象显示,这种看法是正确的。
24+
25+
12月初,特朗普宣布将提名前美国证券交易委员会(SEC)委员保罗·阿特金斯(Paul Atkins)担任该机构的主席。
26+
27+
比起即将离任的主席加里·根斯勒(Gary Gensler),阿特金斯被视为更支持加密货币。
28+
29+
这一消息促使比特币的价格飙升至10万美元以上。
30+
31+
“随着特朗普当选,你可以想像在2025年会出现积极的监管政策。同时,一些负面的监管可能会被移除,这将允许银行和其他机构进入这个领域。”渣打银行数字资产研究全球负责人杰弗瑞·肯德里克(Geoffrey Kendrick)表示。
32+
33+
肯德里克特别提到了一项由美国证监会发布的指导文件——SAB121(员工会计公告121号)。自2022年生效以来,这份文件使银行和其他金融机构难以提供加密货币服务。
34+
35+
如果这项规定被废除,可能会有助特朗普兑现他在7月做出的承诺,即让美国成为全球加密货币之都。
36+
37+
如果他实现这一承诺,这将是一次令人瞩目的逆转,因为在2021年的时候,特朗普曾经形容比特币是“骗局”。
38+
39+
一名女子正看向手机里面的聊天机械人图像来源,Getty Images
40+
图像加注文字,你想AI知道你多少东西呢?
41+
AI更加个人化 - 佐伊·克莱曼(Zoe Kleinman), BBC科技编辑
42+
43+
随着人工智慧能(AI)工具进一步融入我们的手机,包括苹果、Google和三星均已推出可以编辑照片、翻译语言和进行网页搜索的服务,我们正处于一个AI成为数码生活内在部分的时代开端,并且在个人层面上变得越来越有用。
44+
45+
不过,这一切需要我们有一定程度的信任和接受。
46+
47+
以日程管理为例,AI工具可以高效地为您管理日程,但这需要你允许它存取你的行程资料。然而,应该开放到什么程度呢?
48+
49+
为了让其能够真正有用,是否意味着它需要知道你希望避免见到哪些人,又或哪些关系是你希望保密的、以及需要对谁保密?
50+
51+
您是否希望它为你提供辅导会面或医疗预约的摘要?
52+
53+
这些都是非常个人的信息,如果因某些漏洞而被泄露,可能会导致非常尴尬甚至严重的后果。你会将这类型的数据交给大型科技公司吗?
54+
55+
微软正在大力推动这一个领域。2024年,微软因展示一款名为“Recall”的AI工具而陷入争议。该工具每隔几秒钟就会截取笔记本电脑桌面的快照,帮助用户定位曾经看到但已记不起的内容。
56+
57+
尽管该产品最终未有正式推出,但微软对坚持其原则,并对该工具进行了一些改变。
58+
59+
“我认为我们正迈向一个根本性的崭新时代,在这个时代中,将会有无所不在、持续存在且非常高效的共事伙伴,伴随在你的日常生活中。”微软AI部门负责人穆斯塔法·苏莱曼(Mustafa Suleyman)最近向BBC表示。
60+
61+
尽管面临挑战,技术研究公司CCS Insight的首席分析师本·伍德(Ben Wood)预计,2025年将会出现更多个性化的AI服务。
62+
63+
“这些服务将通过整合不断更新的数据来源,例如电子邮件、讯息、文件和社交媒体上的互动,不断提供最新的输出结果。这将使AI服务能够根据个人的沟通风格、需求和偏好来进行特定调整。”他表示。
64+
65+
然而,伍德也承认,让AI接触你的个人资料会是一个巨大的挑战。
66+
67+
“信任将会是关键。”伍德说道。
68+
69+
两名工人正在数据中心内工作。图像来源,Getty Images
70+
图像加注文字,明年可能会出现大量投放于数据中心的投资。
71+
数据的移动 - 本·莫里斯(Ben Morris),BBC商业科技编辑
72+
73+
随着更多资金涌入人工智能(AI)领域,对于数据中心的建设需求也将不断增加。
74+
75+
训练和运行AI需要大量的计算能力,以及和最新的电脑晶片和伺服器合作。
76+
77+
根据CCS Insight的数据,在未来五年内,包括Google、微软和Meta在内的最大数据用户可能会在数据中心上投资高达1万亿美元。
78+
79+
仅在欧洲,根据房地产服务公司Savills的预测,从2024年到2028年,数据中心的容量每年将平均增长9%。
80+
81+
然而,这些新设施不太可能建在目前的数据中心枢纽,例如伦敦、法兰克福和阿姆斯特丹。
82+
83+
Savills指出,伦敦的土地价格高达每英亩1,700万英镑,加上有限的电力供应,导致开发商不得不另觅其他地方。
84+
85+
在英国,像剑桥、曼彻斯特和伯明翰等城市有可能会成为下一波数据中心建设的所在地。
86+
87+
在欧洲,布拉格、热那亚、慕尼黑、杜塞尔多夫和米兰等城市也有望成为考虑对象。
88+
89+
英伟达的Blackwell晶片安装在电路板上。图像来源,Getty Images
90+
图像加注文字,热门资产——科技公司将争相获取英伟达的新款电脑晶片。
91+
一些新的数据中心,其核心将配备英伟达(Nvidia)最新的电脑晶片,这家公司主导了AI的晶片市场。
92+
93+
在2024年3月发布的Blackwell晶片,预计将于2025年开始大规模出货。
94+
95+
根据美国银行证券(Bank of America Securities)半导体资深分析师维韦克·阿里亚(Vivek Arya)的说法,这款新晶片应能令科技公司训练AI的速度提高四倍,并让AI运行速度比当前的电脑晶片快30倍。
96+
97+
据报导,英伟达的最大客户包括微软、亚马逊、Meta和Coreweave,这些公司可能会优先获得这项技术。
98+
99+
然而,其他客户可能难以取得这款超级晶片,阿里亚表示,“2025年的供应将会受到限制。”

docs/awesome-rag.md

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
2+
## RAG技巧
3+
4+
- [高级RAG(八): 自动合并检索(Auto-merging Retrieval)](https://zhuanlan.zhihu.com/p/678698001#/)
5+
- [RAG进阶笔记:RAG进阶](https://blog.csdn.net/qq_40206371/article/details/137025939#/)
6+
- [优化RAG索引策略:多向量索引与父文档检索技术](https://www.cnblogs.com/muzinan110/p/18541479#/)
7+
- [高级检索增强生成技术(RAG)全面指南:原理、分块、编码、索引、微调、Agent、展望](https://zhuanlan.zhihu.com/p/673922981#/)
8+
- [使用GPT + RAG项目实战经验总结](https://github.com/AI-Inception/RAG-In-Action/blob/main/README.md#/)

docs/chunks.md

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -79,4 +79,5 @@
7979

8080

8181
### 参考资料
82-
[RAG中常见的chunk切分方法](https://www.ctyun.cn/developer/article/551915360890949)
82+
[RAG中常见的chunk切分方法](https://www.ctyun.cn/developer/article/551915360890949)
83+
[Meta-Chunking](https://github.com/IAAR-Shanghai/Meta-Chunking#/)
Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
import numpy as np
2+
from typing import List
3+
4+
import matplotlib.pyplot as plt
5+
import numpy as np
6+
7+
from trustrag.modules.chunks.semantic_chunk import SemanticChunker
8+
from trustrag.modules.retrieval.embedding import SentenceTransformerEmbedding
9+
10+
def example_usage():
11+
"""
12+
Example demonstrating how to use the SemanticChunker with SentenceTransformerEmbedding.
13+
"""
14+
# Initialize the embedding generator
15+
embedding_generator = SentenceTransformerEmbedding(
16+
model_name_or_path="G:/pretrained_models/mteb/all-MiniLM-L6-v2"
17+
)
18+
19+
# Initialize the semantic chunker
20+
chunker = SemanticChunker(embedding_generator=embedding_generator)
21+
22+
# Example text with clear topic changes
23+
text = """
24+
Machine learning is a field of inquiry devoted to understanding and building methods that 'learn', that is, methods that leverage data to improve performance on some set of tasks. It is seen as a part of artificial intelligence. Machine learning algorithms build a model based on sample data, known as training data, in order to make predictions or decisions without being explicitly programmed to do so. Machine learning algorithms are used in a wide variety of applications, such as in medicine, email filtering, speech recognition, and computer vision, where it is difficult or unfeasible to develop conventional algorithms to perform the needed tasks.
25+
26+
气候变化真的大.
27+
28+
The Python programming language is widely used in machine learning due to its simplicity and the availability of powerful libraries. Libraries such as TensorFlow, PyTorch, and scikit-learn provide tools for implementing machine learning algorithms efficiently. Python's readability makes it ideal for teaching and learning machine learning concepts. Its extensive ecosystem of data science tools also makes it suitable for production environments.
29+
"""
30+
31+
# Get chunks using different methods
32+
percentile_chunks = chunker.get_chunks(text, chunk_method="percentile", threshold=20)
33+
std_dev_chunks = chunker.get_chunks(text, chunk_method="standard_deviation", threshold=1.0)
34+
print(chunker.get_results())
35+
# Get the results
36+
results = chunker.get_results()
37+
38+
# Print the chunks
39+
print(f"Number of chunks using percentile method: {len(percentile_chunks)}")
40+
for i, chunk in enumerate(percentile_chunks):
41+
print(f"/nChunk {i + 1}:")
42+
print(chunk)
43+
44+
# Visualize the similarity scores and breakpoints
45+
visualize_similarities(results["similarities"], results["breakpoints"])
46+
47+
48+
def visualize_similarities(similarities: List[float], breakpoints: List[int]):
49+
"""
50+
Visualize the similarity scores between consecutive sentences and the detected breakpoints.
51+
52+
Args:
53+
similarities: List of similarity scores between consecutive sentences
54+
breakpoints: List of indices where chunk splits occur
55+
"""
56+
plt.figure(figsize=(12, 6))
57+
plt.plot(similarities, marker='o', linestyle='-', markersize=8)
58+
59+
# Highlight breakpoints
60+
for bp in breakpoints:
61+
plt.axvline(x=bp, color='red', linestyle='--', alpha=0.7)
62+
plt.plot(bp, similarities[bp], 'ro', markersize=10)
63+
64+
plt.title('Semantic Similarity Between Consecutive Sentences')
65+
plt.xlabel('Sentence Pair Index')
66+
plt.ylabel('Cosine Similarity')
67+
plt.grid(True, alpha=0.3)
68+
plt.tight_layout()
69+
70+
# Add horizontal line at mean similarity
71+
mean_sim = np.mean(similarities)
72+
plt.axhline(y=mean_sim, color='green', linestyle='--', alpha=0.7,
73+
label=f'Mean Similarity: {mean_sim:.3f}')
74+
75+
plt.legend()
76+
plt.savefig('semantic_chunking_visualization.png')
77+
plt.show()
78+
79+
80+
if __name__ == "__main__":
81+
example_usage()
54.6 KB
Loading

trustrag/modules/chunks/base.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,18 @@
1+
from typing import List, Union
2+
13
class BaseChunker(object):
24
def __init__(self):
35
pass
4-
def get_chunks(self, chunk):
5-
raise NotImplementedError
6+
def get_chunks(self, paragraphs: Union[str, List[str]], chunk_size: int = 64):
7+
raise NotImplementedError
8+
9+
@staticmethod
10+
def check_validation(paragraphs: Union[str, List[str]],chunk_size: int):
11+
# check input validation
12+
if isinstance(paragraphs, str):
13+
paragraphs = [paragraphs]
14+
elif not isinstance(paragraphs, list) or not all(isinstance(p, str) for p in paragraphs):
15+
raise TypeError("The 'paragraphs' parameter must be a string or a list of strings.")
16+
if not isinstance(chunk_size, int) or chunk_size <= 0:
17+
raise ValueError("The 'chunk_size' parameter must be a positive integer.")
18+
return paragraphs
Lines changed: 23 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
1+
from typing import List, Union
12
from trustrag.modules.chunks.base import BaseChunker
2-
from typing import List
3+
34

45
class CharChunker(BaseChunker):
56
"""
@@ -9,38 +10,43 @@ class CharChunker(BaseChunker):
910
input texts into smaller chunks, where each chunk contains a specified number of characters.
1011
This is useful for processing long texts in smaller, manageable pieces.
1112
12-
Attributes:
13-
chunk_size (int): The number of characters per chunk. Defaults to 64.
1413
"""
1514

16-
def __init__(self, chunk_size: int = 64) -> None:
15+
def __init__(self) -> None:
1716
"""
1817
Initializes the CharChunker with a specified chunk size.
1918
20-
Args:
21-
chunk_size (int): The number of characters per chunk. Defaults to 64.
2219
"""
2320
super().__init__()
24-
self.chunk_size = chunk_size
2521

26-
def get_chunks(self, paragraphs: List[str]) -> List[str]:
22+
def get_chunks(self, paragraphs: Union[str, List[str]], chunk_size: int = 64) -> List[str]:
2723
"""
2824
Splits the input paragraphs into chunks of characters based on the specified chunk size.
2925
3026
Args:
31-
paragraphs (List[str]): A list of strings (paragraph) to be chunked.
27+
paragraphs (Union[str, List[str]]): A string or a list of strings (paragraphs) to be chunked.
28+
chunk_size (int): The size of each chunk.
3229
3330
Returns:
3431
List[str]: A list of chunks, where each chunk is a string of characters.
32+
33+
Raises:
34+
ValueError: If chunk_size is not a positive integer.
35+
TypeError: If paragraphs is not a string or a list of strings.
3536
"""
36-
chunks = []
37-
for paragraph in paragraphs:
38-
for i in range(0, len(paragraph), self.chunk_size):
39-
chunk = paragraph[i:i + self.chunk_size]
40-
chunks.append(chunk)
37+
# check input valid
38+
paragraphs=self.check_validation(paragraphs=paragraphs, chunk_size=chunk_size)
39+
# use list comprehension to optimize performance
40+
chunks = [
41+
paragraph[i:i + chunk_size]
42+
for paragraph in paragraphs
43+
for i in range(0, len(paragraph), chunk_size)
44+
]
4145
return chunks
4246

43-
4447
if __name__ == "__main__":
45-
cc = CharChunker(chunk_size=64)
46-
print(cc.get_chunks(["我喜欢北京。"]))
48+
cc = CharChunker()
49+
with open("../../../data/docs/伊朗总统罹难事件.txt","r",encoding="utf-8") as f:
50+
content=f.read()
51+
print(cc.get_chunks([content],chunk_size=128))
52+
print(cc.get_chunks(content,chunk_size=128))

0 commit comments

Comments
 (0)