pandas 数据分析 panda处理数据 - a"
panda处理数据
0、panda读写1、panda读写excel2、panda读写parquet3、panda读写csv和txt1.批量读取csv2.批量读取txt3、批量读取parquet
4、panda不同格式文件chunk读写5、读取不同格式的文件并用llm处理1、翻译2、词表扩展3、多关键字提示词组合
0、panda读写
# pandasVersusExcel
# http://sa.mentorx.net/course/89/tasks
# 第一课 创建文件
# 2018-10-17
# 1、创建列
import pandas as pd
df = pd.DataFrame({'ID':[0,1,2],'Name':['Mark','Tomi','Jack']})
# 此处设置数据表的索引,如未设置索引会自动在最前方添加一列作为索引
df = df.set_index('ID') # 会生成新的 DataFrame
# df.set_index('ID',inplace=True) # 在原来的 DataFrame 上进行修改
# 将数据报错到 output.xlsx
df.to_excel('./output.xlsx')
print(df)
print('Done')
column_data = [
['Piccola Cucina Estiatorio', 'Italian', 4.6],
['Boucherie West Village', 'French', 4.6],
['Mei Jin Ramen', 'Japanese', 4.5],
['Spice Symphony', 'Indian', 4.4],
['Bua Thai Ramen & Robata Grill', 'Thai', 4.5]
]
df_data = pd.DataFrame(
data=column_data,
columns=['Restaurant', 'Cuisine', 'Rating']
)
print(df_data)
#2、创建表和列,单个DataFrame
#参考:https://pythonbasics.org/write-excel/
import pandas as pd
import openpyxl
# df = pd.DataFrame({'ID':[0,1,2],'Name':['Mark','Tomi','Jack']}) #多种形式
df = pd.DataFrame([[11, 21, 31], [12, 22, 32], [31, 32, 33]],
index=['one', 'two', 'three'], columns=['a', 'b', 'c']) #第一个参数为data
# df = pd.DataFrame(data=[[11, 21, 31], [12, 22, 32], [31, 32, 33]],
# index=['one', 'two', 'three'], columns=['a', 'b', 'c'])
print(df)
df.to_excel('./output2.xlsx', sheet_name='new_sheet_name')
# # If you do not need to write index (row name), columns (column name),
# # the argument index, columns is False.
# df.to_excel('pandas_to_excel_no_index_header.xlsx', index=False, header=False)
# 3、创建表和列,多个DataFrame,Write Multiple sheets
df2 = df[['a', 'c']] #只获取df的某列
print(df2)
with pd.ExcelWriter('./mutilFrame_write_excel.xlsx') as writer:
df.to_excel(writer, sheet_name='sheet1')
df2.to_excel(writer, sheet_name='sheet2')
#Append to an existing Excel file
#写到已经存在文件
path = './output2.xlsx'
with pd.ExcelWriter(path,mode='a') as writer:
# writer.book = openpyxl.load_workbook(path)
df.to_excel(writer, sheet_name='new_sheet3')
df2.to_excel(writer, sheet_name='new_sheet4')
#创建空表
# df_empt = pd.DataFrame() #第一个参数为data
df_empt = pd.DataFrame(columns=['a', 'b', 'c']) #第一个参数为data
df_empt.to_excel('./emty_file.xlsx', sheet_name='new_sheet_name')
# 打开现有的Excel文件
excel_file = pd.read_excel('./emty_file.xlsx')
print('excel_file:',excel_file)
#4、追加数据
df_add = pd.DataFrame([[1100, 2100, 3100], [1200, 22000, 3200], [3100, 3200, 3300]],
index=['one', 'two', 'three'], columns=['a', 'b', 'c']) #第一个参数为data
path = './output2.xlsx'
with pd.ExcelWriter(path, engine='openpyxl', mode='a',if_sheet_exists='overlay') as writer:
df1 = pd.DataFrame(pd.read_excel(path, sheet_name='new_sheet3'))
df_rows = df1.shape[0] #获取原数据的行数
#将数据df写入excel中的sheet1表,从第一个空行开始写:
df_add.to_excel(writer, sheet_name='new_sheet3',startrow=df_rows+1, header=False)
# df_add.to_excel(writer, sheet_name='new_sheet3',startrow=df_rows+1, index=False, header=False)
#4、追加数据
df_add = pd.DataFrame([[1100, 2100, 3100], [1200, 22000, 3200], [3100, 3200, 3300]],
index=['one', 'two', 'three'], columns=['a', 'b', 'c']) #第一个参数为data
path = './emty_file.xlsx'
with pd.ExcelWriter(path, engine='openpyxl', mode='a',if_sheet_exists='overlay') as writer:
df1 = pd.DataFrame(pd.read_excel(path, sheet_name='new_sheet_name'))
df_rows = df1.shape[0] #获取原数据的行数
#将数据df写入excel中的sheet1表,从第一个空行开始写:
df_add.to_excel(writer, sheet_name='new_sheet_name',startrow=df_rows+1, header=False)
# df_add.to_excel(writer, sheet_name='new_sheet3',startrow=df_rows+1, index=False, header=False)
#5、相关参数说明参考
# 参考:https://pandas.pydata.org/docs/reference/api/pandas.ExcelWriter.html
# You can also append to an existing Excel file:
# with pd.ExcelWriter("path_to_file.xlsx", mode="a", engine="openpyxl") as writer:
# df.to_excel(writer, sheet_name="Sheet3")
# Here, the if_sheet_exists parameter can be set to replace a sheet if it already exists:
# with ExcelWriter(
# "path_to_file.xlsx",
# mode="a",
# engine="openpyxl",
# if_sheet_exists="replace",
# ) as writer:
# df.to_excel(writer, sheet_name="Sheet1")
# You can also write multiple DataFrames to a single sheet. Note that the if_sheet_exists parameter needs to be set to overlay:
# with ExcelWriter("path_to_file.xlsx",
# mode="a",
# engine="openpyxl",
# if_sheet_exists="overlay",
# ) as writer:
# df1.to_excel(writer, sheet_name="Sheet1")
# df2.to_excel(writer, sheet_name="Sheet1", startcol=3)
# pandasVersusExcel
# http://sa.mentorx.net/course/89/tasks
# 第二课 读取文件
# 2018-10-17
# import os
# os.chdir(os.path.dirname(__file__))
import pandas as pd
# --基本数据的读取--
# 读取文件
# head:默认0,表示开始读取的行(默认会跳过顶部的空行)
# index_col: 指定数据的索引列
people = pd.read_excel('./People.xlsx',header=0,index_col='ID',dtype={'ID': str})
print('people:',people)
# 读取文件的行数和列数
shape = people.shape
print('shape:',shape)
# 读取文件的行,不会显示索引列
columns = people.columns
print('columns:',columns)
# 读取文件的前几行(默认为5,可传入指定行数)
head = people.head()
print('head:',head)
# 读取文件的末尾几行(默认为5,可传入指定行数)
tail = people.tail()
print('tail:',tail)
# --当数据文件存在坏数据时可按以下方式处理--
# (以下内容根据实际情况使用,同时使用会造成数据混乱)
# 当标题行上有坏数据时可使用 head 参数
people1 = pd.read_excel('./People.xlsx',header=1)
# 当数据表中没有标题行时可将 head 的值设为 None 表示无标题
people2 = pd.read_excel('./People.xlsx',header=None)
people2.columns = ['ID', 'Type', 'Title', 'FirstName', 'MiddleName', 'LastName']
print('peolpe2:',people2)
print(columns)
people格式如下:
people: Type Title FirstName MiddleName LastName
ID
1 Employee NaN Ken J Sánchez
2 Employee NaN Terri Lee Duffy
3 Employee NaN Roberto NaN Tamburello
4 Employee NaN Rob NaN Walters
5 Employee Ms. Gail A Erickson
... ... ... ... ... ...
20773 Individual Customer NaN Crystal NaN Guo
20774 Individual Customer NaN Isabella F Richardson
20775 Individual Customer NaN Crystal S He
20776 Individual Customer NaN Crystal NaN Zheng
20777 Individual Customer NaN Crystal NaN Hu
# pandasVersusExcel
# http://sa.mentorx.net/course/89/tasks
# 第二课 读取文件
# 2018-10-17
# import os
# os.chdir(os.path.dirname(__file__))
#1、获取基本数据
import pandas as pd
# --基本数据的读取--
# 读取文件
# head:默认0,表示开始读取的行(默认会跳过顶部的空行)
# index_col: 指定数据的索引列
people = pd.read_excel('./People.xlsx',header=0,index_col='ID',dtype={'ID': str})
print('people:',people)
# 读取文件的行数和列数
shape = people.shape
print('shape:',shape)
# 读取文件的行,不会显示索引列
columns = people.columns
print('columns:',columns)
# 读取文件的前几行(默认为5,可传入指定行数)
head = people.head()
print('head:',head)
# 读取文件的末尾几行(默认为5,可传入指定行数)
tail = people.tail()
print('tail:',tail)
# --当数据文件存在坏数据时可按以下方式处理--
# (以下内容根据实际情况使用,同时使用会造成数据混乱)
# 当标题行上有坏数据时可使用 head 参数
people1 = pd.read_excel('./People.xlsx',header=1)
# 当数据表中没有标题行时可将 head 的值设为 None 表示无标题
people2 = pd.read_excel('./People.xlsx',header=None)
people2.columns = ['ID', 'Type', 'Title', 'FirstName', 'MiddleName', 'LastName']
print('peolpe2:',people2)
print(columns)
print('...................................\n')
#2、获取行列数据
# 参考:https://pandas.pydata.org/docs/reference/api/pandas.read_excel.html
# 参考:https://www.digitalocean.com/community/tutorials/pandas-read_excel-reading-excel-file-in-python
import pandas
excel_data_df = pandas.read_excel('./People.xlsx', sheet_name=0,index_col=None, header=0) #header指定列名所在的行
# print whole sheet data
print(' whole sheet data:',excel_data_df)
print('列名:',excel_data_df.columns.ravel())
# print('某列的数据:',excel_data_df['FirstName'].tolist())
print('某列的前几个数据:',excel_data_df['FirstName'].tolist()[:3])
import pandas
excel_data_df = pandas.read_excel('./People.xlsx', sheet_name=0, usecols=['FirstName', 'MiddleName'])
print('只读取表某几列:\n',excel_data_df)
#转成其他格式
# 6. Excel Sheet to Dict, CSV and JSON
# The DataFrame object has various utility methods to convert the tabular data into Dict, CSV, or JSON format.
# excel_data_df = pandas.read_excel('records.xlsx', sheet_name='Cars', usecols=['Car Name', 'Car Price'])
excel_data_df = pandas.read_excel('./People.xlsx', sheet_name=0, usecols=['FirstName', 'MiddleName'])
print('Excel Sheet to Dict:', excel_data_df.to_dict(orient='records')[:6]) #取前6个
print('Excel Sheet to JSON:', excel_data_df.to_json(orient='records')[:16])
print('Excel Sheet to CSV:\n', excel_data_df.to_csv(index=False)[:16])
# DataFrame.to_dict(orient='dict')
# 将DataFrame格式的数据转化成字典形式
# 参数:当然参数orient可以是字符串{'dict', 'list', 'series', 'split', 'records', 'index'}中的任意一种来决定字典中值的类型
# 链接:https://blog.csdn.net/weixin_45177786/article/details/119794169
#合并多个sheet
# pandas.concat和DataFrame.append两种方法合并数据,以及相关的参数和示例。concat可以按行或按列合并多个dataframe或series
# https://www.dataquest.io/blog/excel-and-pandas/
# movies = pd.concat([movies_sheet1, movies_sheet2, movies_sheet3])
# movies.shape
#创建多个sheet
df1 = pd.DataFrame(data=[[11, 21, 31], [12, 22, 32], [31, 32, 33]],columns=['a1', 'b1', 'c1']) #第一个参数为data
df2 = pd.DataFrame(data=[['kdee', 'ott', 'ff'], ['dfe', 'dfe', 'dd'], [1, 32, 33]],columns=['a1', 'f1', 'f1']) #第一个参数为data
df3 = pd.DataFrame(data=[['kdee', 'ott', 'ff'], ['dfe', 'dfe', 'dd'], [1, 32, 33]],columns=['g1', 'g2', 'g3']) #第一个参数为data
with pd.ExcelWriter('./mutil_sheet_excel.xlsx') as writer:
df1.to_excel(writer, sheet_name='sheet1')
df2.to_excel(writer, sheet_name='sheet2')
df3.to_excel(writer, sheet_name='sheet3')
new_excel = pd.read_excel('./mutil_sheet_excel.xlsx')
print('创建多个sheet:\n',new_excel)
#读取所有sheet,并合并
# Using the ExcelFile class to read multiple sheets
# We can also use the ExcelFile class to work with multiple sheets from the same Excel file. We first wrap the Excel file using ExcelFile and then pass it to read_excel method.
#https://www.dataquest.io/blog/excel-and-pandas/
excel_file='./mutil_sheet_excel.xlsx'
xlsx = pd.ExcelFile(excel_file)
movies_sheets = []
for sheet in xlsx.sheet_names:
movies_sheets.append(xlsx.parse(sheet))
movies = pd.concat(movies_sheets)
print('movies数据:\n',movies)
print('列名:',movies.columns.ravel())
#读取所有sheet
# Load multiple sheets
# https://pythonbasics.org/read-excel/
df_sheet_multi = pd.read_excel('./mutil_sheet_excel.xlsx', sheet_name=[0, 'sheet2'])
print('读取所有sheet:\n',df_sheet_multi)
# Then you can use it like this:
# print(df_sheet_multi[0])
# print(df_sheet_multi['sheet2'])
# Load all sheets
# If sheet_name argument is none, all sheets are read.
df_sheet_all = pd.read_excel('./mutil_sheet_excel.xlsx', sheet_name=None,index_col=0)
print('df_sheet_all数据:\n',df_sheet_all)
# 创建一个空的DataFrame用于存储合并的数据
merged_df = pd.DataFrame()
# 遍历每个工作表并合并数据
for sheet_name, sheet_data in df_sheet_all.items():
# 将当前工作表数据添加到合并的DataFrame
merged_df = pd.concat([merged_df, sheet_data], ignore_index=True)
print('sheet_name名:',sheet_name)
print('sheet_data数据:\n',sheet_data)
# 打印合并的DataFrame
print('df_sheet_all合并数据:\n',merged_df)
#Pandas处理csv,excel文件多出unnamed列问题
# 开始查到的方法是添加属性:
# df = pd.read_csv('data.csv', index_col=0)
# df = df.to_csv('data.csv', index=False)
# 后来在stackoverflow上查到可以直接删除包含unname的字段,虽然感觉方法笨一点但是是有效的。
# data = data.loc[:, ~data.columns.str.contains('Unnamed')]
# 读取所有文件所有sheet,相关列的数据并存入字典
import os
dir_path = './'
files = os.listdir(dir_path)
image_files = [file for file in files if file.endswith('.xlsx') or file.endswith('.png')]
print(image_files)
for key in image_files:
# file_name, file_extension = os.path.splitext(key)
name,suffix = key.split(".")
print(name,suffix)
refer=['测试问题','关键词']
data_dict={}
import pandas as pd
files = os.listdir('./')
for file in files :
if file.endswith('.xlsx'):
# df_sheet_all = pd.read_excel(file, sheet_name=None,index_col=0)
df_sheet_all = pd.read_excel(file, sheet_name=None,index_col=None, header=0)
# print('df_sheet_all数据:\n',df_sheet_all)
for sheet_name, sheet_data in df_sheet_all.items():
# 将当前工作表数据添加到合并的DataFrame
# merged_df = pd.concat([merged_df, sheet_data], ignore_index=True)
print('sheet_name名:',sheet_name)
# print('sheet_data数据:\n',sheet_data)
print('列名:',sheet_data.columns.ravel())
include=[i for i in sheet_data.columns.ravel() if i in refer]
for key in include:
# print('某列的前几个数据:',sheet_data[key].tolist()[:3])
data_dict[f'{file.split(".")[0]}_{sheet_name}_{key}']=sheet_data[key].tolist()[:3]
print('所有数据:\n',data_dict)
1、panda读写excel
matplotlib、numpy、pandas是入行数据分析的三个必须掌握的基础模块。Python作为一种强大的编程语言,提供了多种库来读取和处理Excel文件,其中最常用的是pandas库配合openpyxl或xlrd等引擎。 读取所有文件所有sheet,相关列的数据并存入字典
import os
dir_path = './'
files = os.listdir(dir_path)
image_files = [file for file in files if file.endswith('.xlsx') or file.endswith('.png')]
print(image_files)
for key in image_files:
# file_name, file_extension = os.path.splitext(key)
name,suffix = key.split(".")
print(name,suffix)
refer=['测试问题','关键词']
data_dict={}
import pandas as pd
files = os.listdir('./')
for file in files :
if file.endswith('.xlsx'):
# df_sheet_all = pd.read_excel(file, sheet_name=None,index_col=0)
df_sheet_all = pd.read_excel(file, sheet_name=None,index_col=None, header=0)
# print('df_sheet_all数据:\n',df_sheet_all)
for sheet_name, sheet_data in df_sheet_all.items():
# 将当前工作表数据添加到合并的DataFrame
# merged_df = pd.concat([merged_df, sheet_data], ignore_index=True)
print('sheet_name名:',sheet_name)
# print('sheet_data数据:\n',sheet_data)
print('列名:',sheet_data.columns.ravel())
include=[i for i in sheet_data.columns.ravel() if i in refer]
for key in include:
#1、列表格式
# print('某列的前几个数据:',sheet_data[key].tolist()[:3])
data_dict[f'{file.split(".")[0]}_{sheet_name}_{key}']=sheet_data[key].tolist()[:3]
# data_dict[f'{file.split(".")[0]}_{sheet_name}_{key}']=sheet_data[key].tolist()
#2、字典格式
# data_dict[f'{file.split(".")[0]}_{sheet_name}_{key}']=list(sheet_data[key].to_dict().items())[:3]
# data_dict[f'{file.split(".")[0]}_{sheet_name}_{key}']=sheet_data[key].to_dict()
print('所有数据:\n',data_dict)
分块读取: chunksize没有实现,需要手动实现
#获取文件的编码格式
import chardet
def get_encoding(file):
with open(file, 'rb') as f:
tmp = chardet.detect(f.read())
return tmp['encoding']
print('*'*100)
import os
# refer=['测试问题','关键词']
# refer=['关键词']
refer=['cate', 'sentence', 'gt_label', 'shumei', 'pred_label',
'shumei_riskLabel1', 'pred_riskLabel1', 'pred_allLabels', ]
data_dict={}
import pandas as pd
files = os.listdir('./data')
for file in files :
if file.endswith('.xlsx'):
# df_sheet_all = pd.read_excel(file, sheet_name=None,index_col=0)
print('./data/'+file)
df_sheet_all = pd.read_excel('./data/'+file, sheet_name=None,index_col=None, header=0)
# print('df_sheet_all数据:\n',df_sheet_all)
for sheet_name, sheet_data in df_sheet_all.items():
# 将当前工作表数据添加到合并的DataFrame
# merged_df = pd.concat([merged_df, sheet_data], ignore_index=True)
print('sheet_name名:',sheet_name)
# print('sheet_data数据:\n',sheet_data)
print('列名:',sheet_data.columns.ravel())
# 手动分块处理
chunksize=100
for start in range(0, len(sheet_data), chunksize):
df_chunk = sheet_data.iloc[start:start + chunksize]
# process_chunk(df_chunk)
print(df_chunk)
include=[i for i in df_chunk.columns.ravel() if i in refer]
for key in include:
#1、列表格式
print(f'{key}列的前几个数据:',df_chunk[key].tolist()[:3])
追加写入:
import pandas as pd
# 定义读取 Excel 文件的路径
input_file_path = './data/评测端侧安全服务.xlsx'
output_file_path = './data/witer_test.xlsx'
# 获取所有 sheet 的名称
sheet_names = pd.ExcelFile(input_file_path).sheet_names
import os
# 创建一个空的DataFrame
empty_df = pd.DataFrame()
if not os.path.exists(output_file_path):
# 将空的DataFrame保存为Excel文件
print('文件不存在')
empty_df.to_excel(output_file_path, engine='openpyxl', index=False)
# 创建一些示例数据
data = {
'Column1': [1, 2, 3],
'Column2': ['A', 'B', 'C']
}
df = pd.DataFrame(data)
# # 使用ExcelWriter追加写入数据
# with pd.ExcelWriter('empty_example.xlsx', engine='openpyxl', mode='a') as writer:
# df.to_excel(writer, sheet_name='Sheet1', index=False)
select_sheet=["case明细"]
# 创建一个新的 ExcelWriter 对象,用于将数据写入新的 Excel 文件 overlay if_sheet_exists='replace'
with pd.ExcelWriter(output_file_path, engine='openpyxl', mode='a',if_sheet_exists='overlay') as writer:
# for sheet_name in sheet_names:
for sheet_name in sheet_names:
if sheet_name in select_sheet:
#获取原数据的行数
if sheet_name in pd.ExcelFile(output_file_path).sheet_names : #如何sheet存在
df1 = pd.DataFrame(pd.read_excel(output_file_path, sheet_name=sheet_name))
df_rows = df1.shape[0] #获取原数据的行数
else :
df_rows = 0 #获取原数据的行数
print(f"Reading sheet: {sheet_name}")
# 读取整个 sheet 的数据
df = pd.read_excel(input_file_path, sheet_name=sheet_name)
# 将数据写入新的 Excel 文件的对应 sheet
# df.to_excel(writer, sheet_name=sheet_name, index=False)
df_chunk = df.iloc[0:3]
print('写入数据:',df_chunk)
# 将数据写入新的 Excel 文件的对应 sheet
df_chunk.to_excel(writer, sheet_name=sheet_name, startrow=df_rows+1,index=False, header=False)
print(f"Data has been successfully written to {output_file_path}")
# 定义读取 Excel 文件的路径
# file_path = './data/评测端侧安全服务.xlsx'
# 获取所有 sheet 的名称
sheet_names = pd.ExcelFile(output_file_path).sheet_names
# 遍历每个 sheet 并读取数据
for sheet_name in sheet_names:
print(f"Reading sheet: {sheet_name}")
# 使用 pd.read_excel 读取数据块
chunk_iter = pd.read_excel(output_file_path, sheet_name=sheet_name)
print('读取数据:',chunk_iter)
print(len(chunk_iter))
print('sheet个数:',len(sheet_names))
项目案例: 分块chunk读取xlsx文件中数据,跳过前面多少行只对后面数据做处理,将后面处理完的结果写回对应的位置。
import requests
import json
#1、本地模型接口
def post_securmodel(data):
url = "http://12.31.28.3:8057/v1/security/"
headers = {
'Content-Type': 'application/json'
}
# payload = json.dumps({"input": ["1.输入数据","数据2"]})
# payload = json.dumps({"input": data})
# response = requests.request("POST", url, headers=headers, data=payload)
all_label=[]
all_level=[]
all_labels=[]
# print(text)
if isinstance(data, str):
data=[data]
try:
payload = json.dumps({"input": data})
response = requests.request("POST", url, headers=headers, data=payload)
res_dict=response.json()
# print(res.json())
print('请求成功')
except Exception as e:
print(f'请求失败:{e}')
all_label=['请求失败']*len(data)
all_level=['请求失败']*len(data)
all_labels=[[]]*len(data)
if response.json()['code']!='1100':
all_label=['请求失败']*len(data)
all_level=['请求失败']*len(data)
all_labels=[[]]*len(data)
print(response.text)
print(response.json())
for data in response.json()['data']:
all_label.append(data['label'])
if data['label']=='pass':all_level.append('PASS')
else: all_level.append('REJECT')
# all_labels.append(data['all_labels'])
all_labels.append(str(data['all_labels']))
return all_label,all_level,all_labels
# return response.json()
#2、数美接口
import requests
import pandas as pd
from io import BytesIO
import time
from openpyxl import load_workbook
def shumei_api(text_list):
url = 'http://api.com/text/v4'
access_key = 'rdeeefe'
uid = 'None'
payload = {
'accessKey': access_key, 拼多多帮助力入口
'appId': 'default',
'eventId': 'input',
'type': 'TEXTRISK',
'kbType': 'PKB',
'data': {
'text': '',
'tokenId': uid,
}
}
all_label=[]
all_level=[]
# print(text)
if isinstance(text_list, str):
text_list=[text_list]
for text in text_list:
payload['data']['text']=text
try:
res = requests.post(url, json=payload)
res_dict=res.json()
# print(res.json())
print('请求成功')
except Exception as e:
print(f'请求失败:{e}')
all_label.append('请求失败')
all_level.append('请求失败')
continue
if res.json()['code']!=1100:
all_label.append('请求失败')
all_level.append('请求失败')
continue
# res = requests.post(url, json=payload)
# print('.............................................\n')
# print('返回:',res)
# print(res.json())
# print('状态码',res.json()['code'])
# print('状态码',res.json()['riskLabel1'])
# print('状态码',res.json()['riskLevel'])
all_label.append(res.json()['riskLabel1'])
all_level.append(res.json()['riskLevel'])
return all_label,all_level
# 追加写入
def saveap_pf(input_file_path,output_file_path,sheet_name,df_chunk):
if not os.path.exists(output_file_path):
# 创建一个空的DataFrame
empty_df = pd.DataFrame()
# 将空的DataFrame保存为Excel文件
print('文件不存在')
empty_df.to_excel(output_file_path, engine='openpyxl', index=False)
# 创建一个新的 ExcelWriter 对象,用于将数据写入新的 Excel 文件 overlay if_sheet_exists='replace'
with pd.ExcelWriter(output_file_path, engine='openpyxl', mode='a',if_sheet_exists='overlay') as writer:
#获取原数据的行数
if sheet_name in pd.ExcelFile(output_file_path).sheet_names : #如何sheet存在
df1 = pd.DataFrame(pd.read_excel(output_file_path, sheet_name=sheet_name))
df_rows = df1.shape[0] #获取原数据的行数
df_chunk.to_excel(writer, sheet_name=sheet_name, startrow=df_rows+1,index=False, header=False)
else :
df_rows = -1 #获取原数据的行数
df_chunk.to_excel(writer, sheet_name=sheet_name, startrow=df_rows+1,index=False, header=True)
print(f"Data has been successfully written to {output_file_path}")
#获取文件的编码格式
import chardet
def get_encoding(file):
with open(file, 'rb') as f:
tmp = chardet.detect(f.read())
return tmp['encoding']
print('*'*100)
import os
# refer=['测试问题','关键词']
# refer=['关键词']
# refer=['cate', 'sentence', 'gt_label', 'shumei', 'pred_label',
# 'shumei_riskLabel1', 'pred_riskLabel1', 'pred_allLabels', ] #列
refer=['sentence'] #列
data_dict={}
import pandas as pd
files = os.listdir('./data')
for file in files :
if file.endswith('.xlsx'):
# df_sheet_all = pd.read_excel(file, sheet_name=None,index_col=0)
print('./data/'+file)
df_sheet_all = pd.read_excel('./data/'+file, sheet_name=None,index_col=None, header=0)
print('所有sheet:',pd.ExcelFile('./data/'+file).sheet_names)
# print('df_sheet_all数据:\n',df_sheet_all)
for sheet_name, sheet_data in df_sheet_all.items():
# 将当前工作表数据添加到合并的DataFrame
# merged_df = pd.concat([merged_df, sheet_data], ignore_index=True)
print('sheet_name名:',sheet_name)
# print('sheet_data数据:\n',sheet_data)
print('列名:',sheet_data.columns.ravel())
flag=1 #chunk数
# 手动分块处理
chunksize=20
prestar=33363
# prestar=3
df_prerow=sheet_data.iloc[0:prestar]
saveap_pf('./data/'+file,'./save/out_'+file,sheet_name,df_prerow)
for start in range(prestar, len(sheet_data), chunksize):
df_chunk = sheet_data.iloc[start:start + chunksize]
# process_chunk(df_chunk)
# 选多少条输出
flag -=1
if flag<0: break
print('chunk数据:')
print(df_chunk)
include=[i for i in df_chunk.columns.ravel() if i in refer]
for key in include:
#1、列表格式
print(f'{key}列的前几个数据:',df_chunk[key].tolist()[:3])
# mode_data=post_securmodel(df_chunk[key].tolist())
# print('模型返回:',mode_data)
all_risk,all_level,all_labels=post_securmodel(df_chunk[key].tolist())
print('模型返回:',all_risk)
print('模型返回:',all_level)
print('模型返回:',all_labels)
shumei_risk,shumei_level=shumei_api(df_chunk[key].tolist())
print('数美返回:',shumei_risk,shumei_level)
df_chunk.loc[:,'shumei']=shumei_level
df_chunk.loc[:,'shumei_riskLabel1']=shumei_risk
df_chunk.loc[:,'pred_label']=all_level
df_chunk.loc[:,'pred_riskLabel1']=all_risk
df_chunk.loc[:,'pred_allLabels']=all_labels
print('处理后chunk:')
print(df_chunk)
saveap_pf('./data/'+file,'./save/out_'+file,sheet_name,df_chunk)
2、panda读写parquet
https://blog.enterprisedna.co/pandas-read-parquet-file-into-dataframe/ https://stackoverflow.com/questions/33813815/how-to-read-a-parquet-file-into-pandas-dataframe Python提供了多个库来处理Parquet文件,例如pyarrow和fastparquet。panda选择对应库方法: engine {‘auto’, ‘pyarrow’, ‘fastparquet’}, default ‘auto’ Parquet library to use. If ‘auto’, then the option io.parquet.engine is used. The default io.parquet.engine behavior is to try ‘pyarrow’, falling back to ‘fastparquet’ if ‘pyarrow’ is unavailable.
pip install pandas
pip install pyarrow
pip install fastparquet
转换
import pyarrow.parquet as pq
parquet_file = pq.ParquetFile('file.parquet')
data = parquet_file.read().to_pandas()
3、panda读写csv和txt
https://pandas.pydata.org/docs/user_guide/io.html
1.批量读取csv
#1、获取基本数据
import pandas as pd
import numpy as np
df = pd.DataFrame(np.random.randn(10, 4))
# df = pd.DataFrame(np.arange(3,4))
df.to_csv("tmp.csv", index=False)
table = pd.read_csv("tmp.csv")
print('数据:',table)
# 0 1 2 3
# 0 -1.294524 0.413738 0.276662 -0.472035
# 1 -0.013960 -0.362543 -0.006154 -0.923061
# 2 0.895717 0.805244 -1.206412 2.565646
# 3 1.431256 1.340309 -1.170299 -0.226169
# 4 0.410835 0.813850 0.132003 -0.827317
# 5 -0.076467 -1.187678 1.130127 -1.436737
# 6 -1.413681 1.607920 1.024180 0.569605
# 7 0.875906 -2.211372 0.974466 -2.006747
# 8 -0.410001 -0.078638 0.545952 -1.219217
# 9 -1.226825 0.769804 -1.281247 -0.727707
with pd.read_csv("tmp.csv", chunksize=2) as reader:
print('第一批:',reader)
for chunk in reader:
print('chunk数:',chunk)
with pd.read_csv("tmp.csv", iterator=True) as reader :
print('批量:',reader.get_chunk(5))
csv_iter=pd.read_csv("tmp.csv", chunksize=3)
for chunk in csv_iter:
print('chunk数:',chunk)
print('列名:',chunk.columns.ravel())
print('某列的数据:',chunk['1'].tolist())
# print('某列的前几个数据:',chunk['text'].tolist())
2.批量读取txt
https://geek-docs.com/pandas/pandas-read-write/pandas-read-txt.html
#有三种方法可以读取txt
# https://www.programiz.com/python-programming/pandas/text
# We can read text files in Pandas in the following ways:
# Using the read_fwf() function
# Using the read_table() function
# Using the read_csv() function
# John 25 170
# Alice 28 165
# Bob 30 180
# The syntax of read_table() in Pandas is:
# df = pd.read_table(
# filepath_or_buffer,
# sep='\t',
# header='infer',
# names=None
# )
# Here,
# filepath_or_buffer: specifies the path to the file to be read or a URL pointing to the file
# sep: specifies the separator or delimiter used in the file to separate columns
# header: specifies the row number (0-indexed) to be used as the column names
# names: a list of column names for the DataFrame
import pandas as pd
df = pd.DataFrame([[11, 21, 31], [12, 22, 32], [31, 32, 33]],columns=['John', 'Alice', 'Bob']) #第一个参数为data
print('df数据:',df)
# df.to_csv('./data.txt', header=False, index=False, sep='\t')
df.to_csv('./data.txt', header=1, index=False, sep='\t')
# read the file using read_table()
df = pd.read_table("./data.txt", sep="\s+", names=['Name', 'Age', 'Height'])
print('读取:',df)
# read the file using read_table()
df = pd.read_csv("./data.txt", sep="\s+", header = None, names=['Name', 'Age', 'Height'])
print('name读取:',df)
3、批量读取parquet
import pandas as pd
# pd.read_parquet('example_pa.parquet', engine='auto')
# pd.read_parquet('example_pa.parquet', engine='pyarrow')
# pd.read_parquet('example_fp.parquet', engine='fastparquet')
# import pyarrow.parquet as pq
# df = pq.read_table(source=your_file_path).to_pandas()
df = pd.DataFrame({
'student': ['personA007', 'personB', 'x', 'personD', 'personE'],
'marks': [20,10,22,21,22],
})
print('pf数据:\n',df)
df.to_parquet('./sample.parquet')
pf_read = pd.read_parquet('./sample.parquet')
print('pf_read数据:\n',pf_read)
pf_read = pd.read_parquet('./sample.parquet').head(2)
print('pf_read数据:\n',pf_read)
#压缩,Brotli makes for a smaller file and faster read/writes than gzip, snappy, pickle.
# df.to_parquet('df.parquet.brotli',compression='brotli')
# df = pd.read_parquet('df.parquet.brotli')
# df = pd.DataFrame(data={'col1': [1, 2], 'col2': [3, 4]})
# df.to_parquet('df.parquet.gzip', compression='gzip')
# pd.read_parquet('df.parquet.gzip')
# col1 col2
# 0 1 3
# 1 2 4
# #选择列
# dataframe = pd.read_parquet("data.parquet", columns=['id', 'first_name','last_name','email'])
# # 选择行
# df = pd.read_parquet('example.parquet', rows=1000)
# # 合并
# df1 = pd.read_parquet('file1.parquet')
# df2 = pd.read_parquet('file2.parquet')
# df = pd.concat([df1, df2])
# chunk_df读取一部分
import pyarrow.parquet as pq
parquet_file = pq.ParquetFile("./sample.parquet")
for i in parquet_file.iter_batches(batch_size=3):
chunk_df = i.to_pandas()
print('chunk_df读取一部分:\n',chunk_df)
# #dask读取目录
# import dask.dataframe as dd
# df = dd.read_parquet("path/to/directory")
# df = dd.read_parquet("./data/civil_comments/data/train*")
# df = dd.read_parquet("./data/civil_comments/data/")
# computed_df = df.compute()
# print('dask读取目录:\n',computed_df)
#dask读取大文件
import dask.dataframe as dd
# df = dd.read_parquet("path/to/directory")
df = dd.read_parquet("./sample.parquet")
computed_df = df.compute()
print('dask数据:\n',computed_df)
#获取前几条
dask_data=dd.read_parquet("./data/civil_comments/data/test-00000-of-00001.parquet")
computed_dask_data = dask_data.compute()
# print('computed_dask_data数据:\n',computed_dask_data)
print('computed_dask_data数据:\n',computed_dask_data.head(10))
df_head10=computed_dask_data.head(10)
df_head10.to_excel('./df_head10.xlsx')
print('Done')
df_h=pd.read_excel('./df_head10.xlsx')
print(df_h)
print('列名:',df_head10.columns.ravel())
# print('某列的数据:',excel_data_df['FirstName'].tolist())
print('某列的前几个数据:',df_head10['text'].tolist()[:6])
# #dask读取大文件
# import dask.dataframe as dd
# # df = dd.read_parquet("path/to/directory")
# df = dd.read_parquet("./data/civil_comments/data/train*")
# computed_df = df.compute()
# print('dask数据:\n',computed_df)
# #dask读取大文件
# import dask.dataframe as dd
# # df = dd.read_parquet("path/to/directory")
# df = dd.read_parquet("./data/civil_comments/data/train-00001-of-00002.parquet")
# computed_df = df.compute()
# print('dask数据:\n',computed_df)
# #dask读取大文件
# import dask.dataframe as dd
# # df = dd.read_parquet("path/to/directory")
# df = dd.read_parquet("./data/civil_comments/data/train-00000-of-00002.parquet")
# computed_df = df.compute()
# print('dask数据:\n',computed_df)
4、panda不同格式文件chunk读写
#分批读取,处理完读取数据后,追加写回。
import pandas as pd
import openpyxl
import numpy as np
import os
if 1: #是否生成gener新数据文件,创建要处理的数据
# 检查目录是否存在,如果不存在,则创建
directory='./dataset_gener/alldata'
if not os.path.exists(directory):
os.makedirs(directory)
os.makedirs(directory+'_extra')
print(f"目录 '{directory}' 已创建")
# 1、xlsx读写
df1 = pd.DataFrame(np.random.randn(10, 5), columns=['A', 'B', 'C', 'D','N'])
df2 = pd.DataFrame(np.random.randn(10, 5), columns=['E', 'F', 'G', 'H','N'])
# df1.to_excel('./dataset_gener/alldata/out_xlsx1.xlsx', sheet_name='new_sheet_df1')
# df2.to_excel('./dataset_gener/alldata/out_xlsx1.xlsx', sheet_name='new_sheet_df2') #只能写一个sheet,覆盖之前的
#写入多个sheet
with pd.ExcelWriter('./dataset_gener/alldata/out_xlsx2.xlsx',engine='openpyxl') as writer:
df1.to_excel(writer, sheet_name='sheet1', index=False)
df2.to_excel(writer, sheet_name='sheet2', index=False)
# 读取所有sheet
# df_sheet_all1 = pd.read_excel('./dataset_gener/alldata/out_xlsx1.xlsx', sheet_name=None,index_col=0)
df_sheet_all2 = pd.read_excel('./dataset_gener/alldata/out_xlsx2.xlsx', sheet_name=None,index_col=0)
# df_sheet_all2 = pd.read_excel('./dataset_gener/alldata/out_xlsx2.xlsx', sheet_name=None,index_col=False)
# print('Excel_sheet_all1数据:\n',df_sheet_all1)
print('Excel_sheet_all2数据:\n',df_sheet_all2)
print('*'*100)
# 2、parquetd读写
df3 = pd.DataFrame(np.random.randn(10, 4), columns=['A', 'B', 'C', 'D'])
# print('pf3数据:\n',df3)
df3.to_parquet('./dataset_gener/alldata/out_parquet1.parquet')
pf3_read = pd.read_parquet('./dataset_gener/alldata/out_parquet1.parquet')
print('parquetd_read数据:\n',pf3_read)
print('*'*100)
# 3、csv读写
# df = pd.DataFrame(np.random.randn(10, 4))
df4 = pd.DataFrame(np.random.randn(10, 4), columns=['A', 'B', 'C', 'D'])
# df = pd.DataFrame(np.arange(3,4))
df4.to_csv("./dataset_gener/alldata/out_csv1.csv", index=False)
pf4_read = pd.read_csv("./dataset_gener/alldata/out_csv1.csv")
print('csv_read数据:\n',pf4_read)
print('*'*100)
# 4、txt读写
df5 = pd.DataFrame(np.random.randn(10, 4), columns=['A', 'B', 'C', 'D'])
# print('df5数据:',df5)
# df.to_csv('./data.txt', header=False, index=False, sep='\t')
df5.to_csv('./dataset_gener/alldata/out_txt1.txt', header=1, index=False, sep='\t')
# df5.to_csv('./dataset_gener/alldata/out_txt1.txt', header=1, index=False, sep='\n')
# read the file using read_table()
# df = pd.read_table("./data.txt", sep="\s+", names=['Name', 'Age', 'Height'])
pf5_read = pd.read_table("./dataset_gener/alldata/out_txt1.txt", sep="\s+", names=['Name', 'Age', 'Height'])
# 然而,\n这种方法可能会导致读取的数据出现问题,因为换行符通常用于分隔行,而不是列。因此,推荐使用其他分隔符(如逗号、制表符)来分隔列。
# pf5_read = pd.read_table("./dataset_gener/alldata/out_txt1.txt", sep="\n+")
print('txt_read数据:\n',pf5_read)
#获取文件的编码格式,读取txt文件会用到
import chardet
def get_encoding(file):
with open(file, 'rb') as f:
tmp = chardet.detect(f.read())
return tmp['encoding']
def process_chunk():
print('')
# 追加写入
def save_chunk(df_chunk,sheet_name,output_file_path):
if not os.path.exists(output_file_path):
# 创建一个空的DataFrame
empty_df = pd.DataFrame()
# 将空的DataFrame保存为Excel文件
print('文件不存在')
empty_df.to_excel(output_file_path, engine='openpyxl',sheet_name='empty', index=False) #默认会创建一个Sheet1表
# 创建一个新的 ExcelWriter 对象,用于将数据写入新的 Excel 文件 overlay if_sheet_exists='replace'
with pd.ExcelWriter(output_file_path, engine='openpyxl', mode='a',if_sheet_exists='overlay') as writer:
#获取原数据的行数
if sheet_name in pd.ExcelFile(output_file_path).sheet_names : #如果sheet存在,读取行追加
df1 = pd.DataFrame(pd.read_excel(output_file_path, sheet_name=sheet_name))
df_rows = df1.shape[0] #获取原数据的行数
df_chunk.to_excel(writer, sheet_name=sheet_name, startrow=df_rows+1,index=False, header=False)
else :
df_rows = -1 #获取原数据的行数
df_chunk.to_excel(writer, sheet_name=sheet_name, startrow=df_rows+1,index=False, header=True)
print(f"Data has been successfully written to {output_file_path}")
#多格式数据处理
if __name__ == '__main__':
data_dir='./dataset_gener' #数据集路径
out_dir='./dataset_out' #输出的路径
data_col={'sensitive-stop-words':0, 'tencent-sensitive-words':0, 'Sensitive-lexicon':0,'mydata':0} #数据所在的列
chunk_size=3 #推理批大小,和zip的一致,1,2,3设置为6的倍数合适(最小公倍数)
chunknum_file=2 #取多少条,总条数=chunk_size*chunknum_file(每个文件取多少条,测试用)
for dir in next(os.walk(data_dir))[1]: ##遍历子目录
# files = os.listdir(data_dir)
files = os.listdir(f'{data_dir}/{dir}')
print('目录:',dir)
for file in files : #遍历文件
if file.endswith('.parquet_no_use'):
print('文件路径:',f'{dir}/{file}')
file_name,suffix = file.split(".")
print(file_name,suffix)
# #清空jsonl文件
# if os.path.exists(r'./vllm_data.jsonl'):
# os.remove(r'./vllm_data.jsonl')
#清空jsonl文件
file_outpath=f'{out_dir}/{dir}/{file_name}.jsonl'
dir_name=f'{out_dir}/{dir}'
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
if os.path.exists(rf'{file_outpath}'):
os.remove(rf'{file_outpath}')
flag=0
# chunk_df读取一部分
import pyarrow.parquet as pq
# parquet_file = pq.ParquetFile("./data/civil_comments/data/train-00000-of-00002.parquet")
parquet_file = pq.ParquetFile(f'{data_dir}/{dir}/{file}')
for i in parquet_file.iter_batches(chunk_size=chunk_size):
chunk_df = i.to_pandas()
# print('chunk_df读取一部分:\n',chunk_df)
# print('列名:',chunk_df.columns.ravel())
# # print('某列的数据:',excel_data_df['FirstName'].tolist())
# print('某列的前几个数据:',chunk_df['text'].tolist())
# 将DataFrame对象转换为numpy数组
# batch_data_rowsrc = chunk_df.values
# 选多少条输出
# flag +=1
# if flag==5: break
# vllm_data(llm,tokenizer,chunk_df['text'].tolist(),batch_data_rowsrc)
# col_name=data_col[dir]
# dataset_name=dir
# vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,file_outpath)
if file.endswith('.csv_no_use'):
print('文件路径:',f'{dir}/{file}')
file_name,suffix = file.split(".")
print(file_name,suffix)
#清空jsonl文件
file_outpath=f'{out_dir}/{dir}/{file_name}.jsonl'
dir_name=f'{out_dir}/{dir}'
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
if os.path.exists(rf'{file_outpath}'):
os.remove(rf'{file_outpath}')
flag=0
# chunk_df读取一部分
csv_iter=pd.read_csv(f'{data_dir}/{dir}/{file}', chunksize=chunk_size)
for chunk_df in csv_iter:
print('chunk数据:',chunk_df)
print('列名:',chunk_df.columns.ravel())
# print('某列的数据:',chunk['1'].tolist())
# print('某列的前几个数据:',chunk['text'].tolist())
# 选多少条输出
# flag +=1
# if flag==5: break
#数据所在的列
# col_name='comment_text'
# col_name=data_col[dir]
# dataset_name=dir
# vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,file_outpath)
if file.endswith('.txt'):
print('文件路径:',f'{dir}/{file}')
file_name,suffix = file.split(".")
print(file_name,suffix)
#清空jsonl文件
dir_name=f'{out_dir}/{dir}'
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
# file_outpath=f'{out_dir}/{dir}/{file_name}.jsonl'
# if os.path.exists(rf'{file_outpath}'):
# os.remove(rf'{file_outpath}')
flag=chunknum_file
# chunk_df读取一部分
# csv_iter=pd.read_csv(f'{data_dir}/{dir}/{file}', chunksize=chunk_size)
csv_iter=pd.read_csv(f'{data_dir}/{dir}/{file}', chunksize=chunk_size,sep="\n+", header = None,skip_blank_lines=True,engine='python',encoding=get_encoding(f'{data_dir}/{dir}/{file}'))
# df = pd.read_csv(f'{path}/{dir}/{file}', sep="\n+", header = None,skip_blank_lines=True,engine='python',encoding=get_encoding(f'{path}/{dir}/{file}'))
for chunk_df in csv_iter:
print('chunk数据:',chunk_df)
print('列名:',chunk_df.columns.ravel())
# print('某列的数据:',chunk['1'].tolist())
# print('某列的前几个数据:',chunk['text'].tolist())
# 选文件多少条输出 ,只测试用
flag -=1
if flag<=0: break
#数据所在的列
# col_name='comment_text'
# col_name=data_col[dir]
# dataset_name=dir
# vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,file_outpath)
if file.endswith('.xlsx'):
print('文件路径:',f'{dir}/{file}')
file_name,suffix = file.split(".")
print(file_name,suffix)
#清空jsonl文件
dir_name=f'{out_dir}/{dir}'
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
# file_outpath=f'{out_dir}/{dir}/{file_name}.jsonl'
# if os.path.exists(rf'{file_outpath}'):
# os.remove(rf'{file_outpath}')
# xlsx没有实现chunk,读取所有数据,再通过切片将数据分成块
df_sheet_all = pd.read_excel(f'{data_dir}/{dir}/{file}', sheet_name=None,index_col=None, header=0)
print('所有sheet:',pd.ExcelFile(f'{data_dir}/{dir}/{file}').sheet_names)
# print('df_sheet_all数据:\n',df_sheet_all)
for sheet_name, sheet_data in df_sheet_all.items():
# 将当前工作表数据添加到合并的DataFrame
# merged_df = pd.concat([merged_df, sheet_data], ignore_index=True)
print('sheet_name名:',sheet_name)
# print('sheet_data数据:\n',sheet_data)
print('列名:',sheet_data.columns.ravel())
# flag=1 #chunk数
flag=chunknum_file
# 手动分块处理
chunksize=chunk_size #chunk大小
prestar=3 #跳过前面多少行再读取
df_prerow=sheet_data.iloc[0:prestar] #将不需要处理的数据写入文件
save_chunk(df_prerow,sheet_name,f'{out_dir}/{dir}/{file}')
# saveap_pf('./data/'+file,'./save/out_'+file,sheet_name,df_prerow)
for start in range(prestar, len(sheet_data), chunksize):
df_chunk = sheet_data.iloc[start:start + chunksize]
# process_chunk(df_chunk)
# 选多少条输出
flag -=1
if flag<0: break
print('chunk数据:')
print(df_chunk)
# df_chunk.loc[:,'newcol']=['addmy']*len(df_chunk)
# df_chunk['newcol']=['addmy']*len(df_chunk)
#处理完chunk数据再写回原来位置,process_chunk,修改列数据
df_chunk.loc[:,'N']=['modify']*len(df_chunk)
save_chunk(df_chunk,sheet_name,f'{out_dir}/{dir}/{file}')
print('处理完成')
5、读取不同格式的文件并用llm处理
GLM-4-9B-Chat-1M模型
1、翻译
#1、数美接口
import requests
import pandas as pd
from io import BytesIO
import time
from openpyxl import load_workbook
url = 'xxx'
access_key = 'xxx'
uid = 'None'
def shumei_api(text):
# print(text)
payload = {
'accessKey': access_key,
'appId': 'default',
'eventId': 'input',
'type': 'TEXTRISK',
'kbType': 'PKB',
'data': {
'text': text,
'tokenId': uid,
}
}
res = requests.post(url, json=payload)
# print('.............................................\n')
# print(res.json())
# print(res.json()['riskLabel1'])
# return res.json()['riskLabel1']
return res.json()
# rest=shumei_api(text)
# print('打标tag:',rest)
#2、加载vllm模型
from transformers import AutoTokenizer
from vllm import LLM, SamplingParams
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "6"
print("CUDA_VISIBLE_DEVICES set to:", os.environ["CUDA_VISIBLE_DEVICES"])
# GLM-4-9B-Chat-1M
# max_model_len, tp_size = 1048576, 4
# 如果遇见 OOM 现象,建议减少max_model_len,或者增加tp_size
max_model_len, tp_size = 131072, 1
model_name = "/nfs2/zhaochuan.cai/czc_data/glm-4-9b-chat"
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
llm = LLM(
model=model_name,
tensor_parallel_size=tp_size,
max_model_len=max_model_len,
trust_remote_code=True,
enforce_eager=True,
# gpu_memory_utilization=0.8,
# GLM-4-9B-Chat-1M 如果遇见 OOM 现象,建议开启下述参数
# enable_chunked_prefill=True,
# max_num_batched_tokens=8192
)
def vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,save_file_path):
# user_messages=['你是谁','给我讲个故事','给我写首歌','分析最近股市行情']
# prompt=[ [{"role": "user", "content": val},] for val in user_messages]
# vllm_data(llm,tokenizer,chunk_df['text'].tolist(),batch_data_rowsrc)
# vllm_data(llm,tokenizer,chunk_df)
# print('Excel Sheet to Dict:', excel_data_df.to_dict(orient='records')[:6]) #取前6个
batch_data_rowsrc=chunk_df.to_dict(orient='records')
user_messages=chunk_df[col_name].tolist()
# prompt=[[{"role": "user", "content": f"""
# 将以下消息翻译成中文,如果是中文直接输出:
# ```{issue}```
# """},] for issue in user_messages]
prompt=[[{"role": "user", "content": f"""将以下消息翻译成中文,如果是中文直接输出:```{issue}```"""},] for issue in user_messages]
# prompt= f"""将以下消息翻译成中文,如果是中文直接输出:```{issue}```"""
stop_token_ids = [151329, 151336, 151338]
sampling_params = SamplingParams(temperature=0, max_tokens=1024, stop_token_ids=stop_token_ids)
inputs = tokenizer.apply_chat_template(prompt, tokenize=False, add_generation_prompt=True)
outputs = llm.generate(prompts=inputs, sampling_params=sampling_params)
# print(outputs[0].outputs[0].text)
# print(outputs)
data=[]
for idx,val in enumerate(outputs):
print(f'\n{idx}原文:',user_messages[idx])
print(f'\n{idx}原文的行:',batch_data_rowsrc[idx])
print(f'{idx}翻译结果:',val.outputs[0].text)
# rest=shumei_api(val.outputs[0].text)
rest={"测试":"测试忽略"}
print('打标tag:',rest)
# data.append({"source":"civil_comments", "sentence":val.outputs[0].text, "shumei":rest, "meta":batch_data_rowsrc[idx].tolist()})
data.append({"source":dataset_name, "sentence":val.outputs[0].text.lstrip("\n").replace("```", ""), "shumei":rest, "meta":batch_data_rowsrc[idx]})
# print(f'\n\n个输出:',i)
# print('')
print('json数据:\n',data)
import json
# 将数据保存为JSONL文件,追加
with open(f'{save_file_path}', 'a') as f:
for item in data:
f.write(json.dumps(item,ensure_ascii=False) + '\n')
# user_messages=['你是谁','给我讲个故事','给我写首歌','分析最近股市行情']
# vllm_data(llm,tokenizer,user_messages)
# quit('测试')
#遍历子目录
# path='./dataset'
# for dir in next(os.walk(path))[1]:
# # data_dir='./data/civil_comments/data/'
# files = os.listdir(f'{path}/{dir}')
# print('目录:',dir)
# for file in files :
# if file.endswith('.parquet') or file.endswith('.csv'):
# print(file)
#3、vllm处理数据
if __name__ == '__main__':
data_dir='./dataset'
out_dir='./data_out_use2'
data_col={"Toxic_Comment_Classification_Challenge":"comment_text","civil_comments":"text"} #数据所在的列
batch_size=10000 #推理批大小
for dir in next(os.walk(data_dir))[1]: ##遍历子目录
# files = os.listdir(data_dir)
files = os.listdir(f'{data_dir}/{dir}')
print('目录:',dir)
for file in files : #遍历文件
if file.endswith('.parquet'):
print(file)
file_name,suffix = file.split(".")
print(file_name,suffix)
# #清空jsonl文件
# if os.path.exists(r'./vllm_data.jsonl'):
# os.remove(r'./vllm_data.jsonl')
#清空jsonl文件
file_outpath=f'{out_dir}/{dir}/{file_name}.jsonl'
dir_name=f'{out_dir}/{dir}'
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
if os.path.exists(rf'{file_outpath}'):
os.remove(rf'{file_outpath}')
# if os.path.exists(rf'./data_out_test/{dir}/{file_name}.jsonl'):
# os.remove(rf'./data_out_test/{dir}/{file_name}.jsonl')
flag=0
# chunk_df读取一部分
import pyarrow.parquet as pq
# parquet_file = pq.ParquetFile("./data/civil_comments/data/train-00000-of-00002.parquet")
parquet_file = pq.ParquetFile(f'{data_dir}/{dir}/{file}')
for i in parquet_file.iter_batches(batch_size=batch_size):
chunk_df = i.to_pandas()
# print('chunk_df读取一部分:\n',chunk_df)
# print('列名:',chunk_df.columns.ravel())
# # print('某列的数据:',excel_data_df['FirstName'].tolist())
# print('某列的前几个数据:',chunk_df['text'].tolist())
# 将DataFrame对象转换为numpy数组
# batch_data_rowsrc = chunk_df.values
# 选多少条输出
# flag +=1
# if flag==5: break
# vllm_data(llm,tokenizer,chunk_df['text'].tolist(),batch_data_rowsrc)
col_name=data_col[dir]
dataset_name=dir
vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,file_outpath)
if file.endswith('.csv'):
print(file)
file_name,suffix = file.split(".")
print(file_name,suffix)
#清空jsonl文件
file_outpath=f'{out_dir}/{dir}/{file_name}.jsonl'
dir_name=f'{out_dir}/{dir}'
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
if os.path.exists(rf'{file_outpath}'):
os.remove(rf'{file_outpath}')
flag=0
# chunk_df读取一部分
csv_iter=pd.read_csv(f'{data_dir}/{dir}/{file}', chunksize=batch_size)
for chunk_df in csv_iter:
print('chunk数:',chunk_df)
print('列名:',chunk_df.columns.ravel())
# print('某列的数据:',chunk['1'].tolist())
# print('某列的前几个数据:',chunk['text'].tolist())
# 选多少条输出
# flag +=1
# if flag==5: break
#数据所在的列
# col_name='comment_text'
col_name=data_col[dir]
dataset_name=dir
vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,file_outpath)
2、词表扩展
#1、数美接口
import requests
import pandas as pd
from io import BytesIO
import time
from openpyxl import load_workbook
url = ''
access_key = ''
uid = 'None'
def shumei_api(text):
# print(text)
payload = {
'accessKey': access_key,
'appId': 'default',
'eventId': 'input',
'type': 'TEXTRISK',
'kbType': 'PKB',
'data': {
'text': text,
'tokenId': uid,
}
}
res = requests.post(url, json=payload)
# print('.............................................\n')
# print(res.json())
# print(res.json()['riskLabel1'])
# return res.json()['riskLabel1']
return res.json()
# rest=shumei_api(text)
# print('打标tag:',rest)
#2、加载vllm模型
from transformers import AutoTokenizer
from vllm import LLM, SamplingParams
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "4"
print("CUDA_VISIBLE_DEVICES set to:", os.environ["CUDA_VISIBLE_DEVICES"])
# GLM-4-9B-Chat-1M
# max_model_len, tp_size = 1048576, 4
# 如果遇见 OOM 现象,建议减少max_model_len,或者增加tp_size
max_model_len, tp_size = 131072, 1
model_name = "/nfs2/zhaochuan.cai/czc_data/glm-4-9b-chat"
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
llm = LLM(
model=model_name,
tensor_parallel_size=tp_size,
max_model_len=max_model_len,
trust_remote_code=True,
enforce_eager=True,
gpu_memory_utilization=0.7,
# GLM-4-9B-Chat-1M 如果遇见 OOM 现象,建议开启下述参数
# enable_chunked_prefill=True,
# max_num_batched_tokens=8192
)
def vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,save_file_path):
# user_messages=['你是谁','给我讲个故事','给我写首歌','分析最近股市行情']
# prompt=[ [{"role": "user", "content": val},] for val in user_messages]
# vllm_data(llm,tokenizer,chunk_df['text'].tolist(),batch_data_rowsrc)
# vllm_data(llm,tokenizer,chunk_df)
# print('Excel Sheet to Dict:', excel_data_df.to_dict(orient='records')[:6]) #取前6个
batch_data_rowsrc=chunk_df.to_dict(orient='records')
user_messages=chunk_df[col_name].tolist()
# prompt=[[{"role": "user", "content": f"""
# 将以下消息翻译成中文,如果是中文直接输出:
# ```{issue}```
# """},] for issue in user_messages]
# prompt=[[{"role": "user", "content": f"""将以下消息翻译成中文,如果是中文直接输出:```{issue}```"""},] for issue in user_messages]
# prompt= f"""将以下消息翻译成中文,如果是中文直接输出:```{issue}```"""
# prompt = f"""请根据提供的'''{issue}'''内容,编写一个句子。"""
prompt=[[{"role": "user", "content": f"""请根据提供的'''{issue}'''内容,编写一个句子,包含以下关键词:{issue}。"""},] for issue in user_messages]
stop_token_ids = [151329, 151336, 151338]
sampling_params = SamplingParams(temperature=0.5, max_tokens=1024, stop_token_ids=stop_token_ids)
inputs = tokenizer.apply_chat_template(prompt, tokenize=False, add_generation_prompt=True)
outputs = llm.generate(prompts=inputs, sampling_params=sampling_params)
# print(outputs[0].outputs[0].text)
# print(outputs)
data=[]
for idx,val in enumerate(outputs):
print(f'\n{idx}原文:',user_messages[idx])
print(f'\n{idx}原文的行:',batch_data_rowsrc[idx])
print(f'{idx}翻译结果:',val.outputs[0].text)
# rest=shumei_api(val.outputs[0].text)
rest={"测试":"测试忽略"}
print('打标tag:',rest)
# data.append({"source":"civil_comments", "sentence":val.outputs[0].text, "shumei":rest, "meta":batch_data_rowsrc[idx].tolist()})
data.append({"source":dataset_name, "sentence":val.outputs[0].text.lstrip("\n").replace("```", ""), "shumei":rest, "meta":batch_data_rowsrc[idx]})
# print(f'\n\n个输出:',i)
# print('')
print('json数据:\n',data)
import json
# 将数据保存为JSONL文件,追加
with open(f'{save_file_path}', 'a') as f:
for item in data:
f.write(json.dumps(item,ensure_ascii=False) + '\n')
# user_messages=['你是谁','给我讲个故事','给我写首歌','分析最近股市行情']
# vllm_data(llm,tokenizer,user_messages)
# quit('测试')
#遍历子目录
# path='./dataset'
# for dir in next(os.walk(path))[1]:
# # data_dir='./data/civil_comments/data/'
# files = os.listdir(f'{path}/{dir}')
# print('目录:',dir)
# for file in files :
# if file.endswith('.parquet') or file.endswith('.csv'):
# print(file)
#获取文件的编码格式,读取txt文件会用到
import chardet
def get_encoding(file):
with open(file, 'rb') as f:
tmp = chardet.detect(f.read())
return tmp['encoding']
#3、vllm处理数据
if __name__ == '__main__':
data_dir='./dataset_Sensitive/data_n'
out_dir='./dataset_out_Sensitive'
data_col={'sensitive-stop-words':0, 'tencent-sensitive-words':0, 'Sensitive-lexicon':0} #数据所在的列
batch_size=1000 #推理批大小
for dir in next(os.walk(data_dir))[1]: ##遍历子目录
# files = os.listdir(data_dir)
files = os.listdir(f'{data_dir}/{dir}')
print('目录:',dir)
for file in files : #遍历文件
if file.endswith('.parquet_no_use'):
print(file)
file_name,suffix = file.split(".")
print(file_name,suffix)
# #清空jsonl文件
# if os.path.exists(r'./vllm_data.jsonl'):
# os.remove(r'./vllm_data.jsonl')
#清空jsonl文件
file_outpath=f'{out_dir}/{dir}/{file_name}.jsonl'
dir_name=f'{out_dir}/{dir}'
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
if os.path.exists(rf'{file_outpath}'):
os.remove(rf'{file_outpath}')
# if os.path.exists(rf'./data_out_test/{dir}/{file_name}.jsonl'):
# os.remove(rf'./data_out_test/{dir}/{file_name}.jsonl')
flag=0
# chunk_df读取一部分
import pyarrow.parquet as pq
# parquet_file = pq.ParquetFile("./data/civil_comments/data/train-00000-of-00002.parquet")
parquet_file = pq.ParquetFile(f'{data_dir}/{dir}/{file}')
for i in parquet_file.iter_batches(batch_size=batch_size):
chunk_df = i.to_pandas()
# print('chunk_df读取一部分:\n',chunk_df)
# print('列名:',chunk_df.columns.ravel())
# # print('某列的数据:',excel_data_df['FirstName'].tolist())
# print('某列的前几个数据:',chunk_df['text'].tolist())
# 将DataFrame对象转换为numpy数组
# batch_data_rowsrc = chunk_df.values
# 选多少条输出
# flag +=1
# if flag==5: break
# vllm_data(llm,tokenizer,chunk_df['text'].tolist(),batch_data_rowsrc)
col_name=data_col[dir]
dataset_name=dir
vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,file_outpath)
if file.endswith('.csv_no_use'):
print(file)
file_name,suffix = file.split(".")
print(file_name,suffix)
#清空jsonl文件
file_outpath=f'{out_dir}/{dir}/{file_name}.jsonl'
dir_name=f'{out_dir}/{dir}'
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
if os.path.exists(rf'{file_outpath}'):
os.remove(rf'{file_outpath}')
flag=0
# chunk_df读取一部分
csv_iter=pd.read_csv(f'{data_dir}/{dir}/{file}', chunksize=batch_size)
for chunk_df in csv_iter:
print('chunk数:',chunk_df)
print('列名:',chunk_df.columns.ravel())
# print('某列的数据:',chunk['1'].tolist())
# print('某列的前几个数据:',chunk['text'].tolist())
# 选多少条输出
# flag +=1
# if flag==5: break
#数据所在的列
# col_name='comment_text'
col_name=data_col[dir]
dataset_name=dir
vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,file_outpath)
if file.endswith('.txt'):
print(file)
file_name,suffix = file.split(".")
print(file_name,suffix)
#清空jsonl文件
file_outpath=f'{out_dir}/{dir}/{file_name}.jsonl'
dir_name=f'{out_dir}/{dir}'
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
if os.path.exists(rf'{file_outpath}'):
os.remove(rf'{file_outpath}')
flag=0
# chunk_df读取一部分
# csv_iter=pd.read_csv(f'{data_dir}/{dir}/{file}', chunksize=batch_size)
csv_iter=pd.read_csv(f'{data_dir}/{dir}/{file}', chunksize=batch_size,sep="\n+", header = None,skip_blank_lines=True,engine='python',encoding=get_encoding(f'{data_dir}/{dir}/{file}'))
# df = pd.read_csv(f'{path}/{dir}/{file}', sep="\n+", header = None,skip_blank_lines=True,engine='python',encoding=get_encoding(f'{path}/{dir}/{file}'))
for chunk_df in csv_iter:
print('chunk数:',chunk_df)
print('列名:',chunk_df.columns.ravel())
# print('某列的数据:',chunk['1'].tolist())
# print('某列的前几个数据:',chunk['text'].tolist())
# 选多少条输出
flag +=1
if flag==5: break
#数据所在的列
# col_name='comment_text'
col_name=data_col[dir]
dataset_name=dir
vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,file_outpath)
3、多关键字提示词组合
#1、数美接口
import requests
import pandas as pd
from io import BytesIO
import time
from openpyxl import load_workbook
url = ''
access_key = ''
uid = 'None'
def shumei_api(text):
# print(text)
payload = {
'accessKey': access_key,
'appId': 'default',
'eventId': 'input',
'type': 'TEXTRISK',
'kbType': 'PKB',
'data': {
'text': text,
'tokenId': uid,
}
}
res = requests.post(url, json=payload)
# print('.............................................\n')
# print(res.json())
# print(res.json()['riskLabel1'])
# return res.json()['riskLabel1']
return res.json()
# rest=shumei_api(text)
# print('打标tag:',rest)
# 2、llm数据生成
def vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,save_file_path):
# user_messages=['你是谁','给我讲个故事','给我写首歌','分析最近股市行情']
# prompt=[ [{"role": "user", "content": val},] for val in user_messages]
# vllm_data(llm,tokenizer,chunk_df['text'].tolist(),batch_data_rowsrc)
# vllm_data(llm,tokenizer,chunk_df)
# print('Excel Sheet to Dict:', excel_data_df.to_dict(orient='records')[:6]) #取前6个
batch_data_rowsrc=chunk_df.to_dict(orient='records')
user_messages=chunk_df[col_name].tolist()
# prompt=[[{"role": "user", "content": f"""
# 将以下消息翻译成中文,如果是中文直接输出:
# ```{issue}```
# """},] for issue in user_messages]
# prompt=[[{"role": "user", "content": f"""将以下消息翻译成中文,如果是中文直接输出:```{issue}```"""},] for issue in user_messages]
# prompt= f"""将以下消息翻译成中文,如果是中文直接输出:```{issue}```"""
# prompt = f"""请根据提供的'''{issue}'''内容,编写一个句子。"""
# prompt=[[{"role": "user", "content": f"""请根据提供的'''{issue}'''内容,编写一个句子,包含以下关键词:{issue}。"""},] for issue in user_messages]
#多个关键字,多个prompt组合
prompt1=[[{"role": "user", "content": f"""请根据提供的'''{x}'''内容,编写一个详细具体的句子,包含以下关键词:{x}。"""},] for x in user_messages]
prompt2=[[{"role": "user", "content": f"""请根据提供的'''{x},{y}'''内容,编写一个详细具体的句子,包含以下关键词:{x},{y}。"""},] for x,y in list(zip(*[iter(user_messages)]*2))]
prompt3=[[{"role": "user", "content": f"""请根据提供的'''{x},{y},{z}'''内容,编写一个详细具体的句子,包含以下关键词:{x},{y},{z}。"""},] for x,y,z in list(zip(*[iter(user_messages)]*3))]
prompt4=[[{"role": "user", "content": f"""内容带负面消极信息,编写一个详细具体的句子,包含以下关键词:{x}。"""},] for x in user_messages]
prompt5=[[{"role": "user", "content": f"""内容带负面消极信息,编写一个详细具体的句子,包含以下关键词:{x},{y}。"""},] for x,y in list(zip(*[iter(user_messages)]*2))]
prompt6=[[{"role": "user", "content": f"""内容带负面消极信息,编写一个详细具体的句子,包含以下关键词:{x},{y},{z}。"""},] for x,y,z in list(zip(*[iter(user_messages)]*3))]
prompt7=[[{"role": "user", "content": f"""内容描述清晰生动,编写一个详细具体的句子,包含以下关键词:{x}。"""},] for x in user_messages]
prompt8=[[{"role": "user", "content": f"""内容描述清晰生动,编写一个详细具体的句子,包含以下关键词:{x},{y}。"""},] for x,y in list(zip(*[iter(user_messages)]*2))]
prompt9=[[{"role": "user", "content": f"""内容描述清晰生动,编写一个详细具体的句子,包含以下关键词:{x},{y},{z}。"""},] for x,y,z in list(zip(*[iter(user_messages)]*3))]
prompt = prompt1 + prompt2+prompt3+ prompt4 + prompt5+prompt6 + prompt7 + prompt8+prompt9
print('\n合并:',prompt) # 输出 [1, 2, 3, 4, 5, 6]
stop_token_ids = [151329, 151336, 151338]
sampling_params = SamplingParams(temperature=0.8,n=3, max_tokens=1024, stop_token_ids=stop_token_ids)
inputs = tokenizer.apply_chat_template(prompt, tokenize=False, add_generation_prompt=True)
outputs = llm.generate(prompts=inputs, sampling_params=sampling_params)
# print(outputs[0].outputs[0].text)
# print(outputs)
data=[]
# for key,output in enumerate(outputs) :
# print(f'\n\n第{key}个n:')
# for key,val in enumerate(output.outputs) :
# print(f'输出{key}:',val.text)
for key,output in enumerate(outputs):
print('*'*100)
# key=int(key/9)
print(f'\n\nbatch中第{key}个数据,包含的n条输出:')
for idx,val in enumerate(output.outputs):
# print(f'\n{idx}原文:',user_messages[key])
# print(f'{idx}原文的行:',batch_data_rowsrc[key])
# print(f'{idx}翻译结果:',val.text)
print(f'\n{idx}原文:',prompt[key]) #组合改用prompt
print(f'{idx}翻译结果:',val.text)
# rest=shumei_api(val.outputs[0].text)
rest={"测试":"测试忽略"}
print('打标tag:',rest)
# data.append({"source":"civil_comments", "sentence":val.outputs[0].text, "shumei":rest, "meta":batch_data_rowsrc[idx].tolist()})
# data.append({"source":dataset_name, "sentence":val.text.lstrip("\n").replace("```", ""), "shumei":rest, "meta":batch_data_rowsrc[key]})
data.append({"source":dataset_name, "sentence":val.text.lstrip("\n").replace("```", ""), "shumei":rest, "meta":prompt[key]}) #组合改用prompt
# print(f'\n\n个输出:',i)
# print('')
print('json数据:\n',data)
import json
# 将数据保存为JSONL文件,追加
with open(f'{save_file_path}', 'a') as f:
for item in data:
f.write(json.dumps(item,ensure_ascii=False) + '\n')
# user_messages=['你是谁','给我讲个故事','给我写首歌','分析最近股市行情']
# vllm_data(llm,tokenizer,user_messages)
# quit('测试')
#遍历子目录
# path='./dataset'
# for dir in next(os.walk(path))[1]:
# # data_dir='./data/civil_comments/data/'
# files = os.listdir(f'{path}/{dir}')
# print('目录:',dir)
# for file in files :
# if file.endswith('.parquet') or file.endswith('.csv'):
# print(file)
#获取文件的编码格式,读取txt文件会用到
import chardet
def get_encoding(file):
with open(file, 'rb') as f:
tmp = chardet.detect(f.read())
return tmp['encoding']
#3、加载vllm模型
from transformers import AutoTokenizer
from vllm import LLM, SamplingParams
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "4"
print("CUDA_VISIBLE_DEVICES set to:", os.environ["CUDA_VISIBLE_DEVICES"])
# GLM-4-9B-Chat-1M
# max_model_len, tp_size = 1048576, 4
# 如果遇见 OOM 现象,建议减少max_model_len,或者增加tp_size
max_model_len, tp_size = 131072, 1
model_name = "/nfs2/zhaochuan.cai/czc_data/glm-4-9b-chat"
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
llm = LLM(
model=model_name,
tensor_parallel_size=tp_size,
max_model_len=max_model_len,
trust_remote_code=True,
enforce_eager=True,
gpu_memory_utilization=0.7,
# GLM-4-9B-Chat-1M 如果遇见 OOM 现象,建议开启下述参数
# enable_chunked_prefill=True,
# max_num_batched_tokens=8192
)
#4、vllm处理数据
if __name__ == '__main__':
data_dir='./dataset_Sensitive/data_n' #数据集路径
out_dir='./dataset_out_Sensitive' #输出的路径
data_col={'sensitive-stop-words':0, 'tencent-sensitive-words':0, 'Sensitive-lexicon':0} #数据所在的列
batch_size=3 #推理批大小,和zip的一致,1,2,3设置为6的倍数合适(最小公倍数)
item_get=3 #取多少条,总条数=batch_size*item_get(每个文件取多少条,测试时用)
for dir in next(os.walk(data_dir))[1]: ##遍历子目录
# files = os.listdir(data_dir)
files = os.listdir(f'{data_dir}/{dir}')
print('目录:',dir)
for file in files : #遍历文件
if file.endswith('.parquet_no_use'):
print(file)
file_name,suffix = file.split(".")
print(file_name,suffix)
# #清空jsonl文件
# if os.path.exists(r'./vllm_data.jsonl'):
# os.remove(r'./vllm_data.jsonl')
#清空jsonl文件
file_outpath=f'{out_dir}/{dir}/{file_name}.jsonl'
dir_name=f'{out_dir}/{dir}'
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
if os.path.exists(rf'{file_outpath}'):
os.remove(rf'{file_outpath}')
# if os.path.exists(rf'./data_out_test/{dir}/{file_name}.jsonl'):
# os.remove(rf'./data_out_test/{dir}/{file_name}.jsonl')
flag=0
# chunk_df读取一部分
import pyarrow.parquet as pq
# parquet_file = pq.ParquetFile("./data/civil_comments/data/train-00000-of-00002.parquet")
parquet_file = pq.ParquetFile(f'{data_dir}/{dir}/{file}')
for i in parquet_file.iter_batches(batch_size=batch_size):
chunk_df = i.to_pandas()
# print('chunk_df读取一部分:\n',chunk_df)
# print('列名:',chunk_df.columns.ravel())
# # print('某列的数据:',excel_data_df['FirstName'].tolist())
# print('某列的前几个数据:',chunk_df['text'].tolist())
# 将DataFrame对象转换为numpy数组
# batch_data_rowsrc = chunk_df.values
# 选多少条输出
# flag +=1
# if flag==5: break
# vllm_data(llm,tokenizer,chunk_df['text'].tolist(),batch_data_rowsrc)
col_name=data_col[dir]
dataset_name=dir
vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,file_outpath)
if file.endswith('.csv_no_use'):
print(file)
file_name,suffix = file.split(".")
print(file_name,suffix)
#清空jsonl文件
file_outpath=f'{out_dir}/{dir}/{file_name}.jsonl'
dir_name=f'{out_dir}/{dir}'
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
if os.path.exists(rf'{file_outpath}'):
os.remove(rf'{file_outpath}')
flag=0
# chunk_df读取一部分
csv_iter=pd.read_csv(f'{data_dir}/{dir}/{file}', chunksize=batch_size)
for chunk_df in csv_iter:
print('chunk数:',chunk_df)
print('列名:',chunk_df.columns.ravel())
# print('某列的数据:',chunk['1'].tolist())
# print('某列的前几个数据:',chunk['text'].tolist())
# 选多少条输出
# flag +=1
# if flag==5: break
#数据所在的列
# col_name='comment_text'
col_name=data_col[dir]
dataset_name=dir
vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,file_outpath)
if file.endswith('.txt'):
print(file)
file_name,suffix = file.split(".")
print(file_name,suffix)
#清空jsonl文件
file_outpath=f'{out_dir}/{dir}/{file_name}.jsonl'
dir_name=f'{out_dir}/{dir}'
if not os.path.isdir(dir_name):
os.makedirs(dir_name)
if os.path.exists(rf'{file_outpath}'):
os.remove(rf'{file_outpath}')
flag=item_get
# chunk_df读取一部分
# csv_iter=pd.read_csv(f'{data_dir}/{dir}/{file}', chunksize=batch_size)
csv_iter=pd.read_csv(f'{data_dir}/{dir}/{file}', chunksize=batch_size,sep="\n+", header = None,skip_blank_lines=True,engine='python',encoding=get_encoding(f'{data_dir}/{dir}/{file}'))
# df = pd.read_csv(f'{path}/{dir}/{file}', sep="\n+", header = None,skip_blank_lines=True,engine='python',encoding=get_encoding(f'{path}/{dir}/{file}'))
for chunk_df in csv_iter:
print('chunk数:',chunk_df)
print('列名:',chunk_df.columns.ravel())
# print('某列的数据:',chunk['1'].tolist())
# print('某列的前几个数据:',chunk['text'].tolist())
# 选文件多少条输出
if flag<=0: break
flag -=1
# if item_get>0:
# item_get=item_get-1
# else:
# break
#数据所在的列
# col_name='comment_text'
col_name=data_col[dir]
dataset_name=dir
vllm_data(llm,tokenizer,chunk_df,col_name,dataset_name,file_outpath)
精彩链接