code
stringlengths 1
1.05M
| repo_name
stringlengths 6
83
| path
stringlengths 3
242
| language
stringclasses 222
values | license
stringclasses 20
values | size
int64 1
1.05M
|
|---|---|---|---|---|---|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
市场数据爬虫 - 负责从农业部网站爬取真实市场价格数据
基于market_crawler.py实现
"""
import requests
import json
import time
import threading
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Any
import logging
import urllib3
from .config import config
from .data_manager import get_data_manager
# 禁用SSL警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class MarketCrawler:
"""市场数据爬虫 - 真实数据版本"""
def __init__(self):
self.config = config.get_crawler_config()
self.data_manager = get_data_manager()
self.is_running = False
self.crawler_thread = None
self.start_time = None
self.crawled_count = 0
self.error_count = 0
# 真实API配置 - 基于农业部官方接口
self.base_url = "https://pfsc.agri.cn/api"
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Content-Type": "application/json;charset=UTF-8",
"Origin": "https://pfsc.agri.cn",
"Referer": "https://pfsc.agri.cn/",
"Connection": "keep-alive",
"sec-ch-ua": '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "Windows",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin"
}
self.timeout = self.config.get('timeout_seconds', 30)
self.retry_times = self.config.get('retry_times', 3)
# 省份列表 - 使用真实的省份代码
self.provinces = [
{"code": "110000", "name": "北京市"},
{"code": "120000", "name": "天津市"},
{"code": "130000", "name": "河北省"},
{"code": "140000", "name": "山西省"},
{"code": "150000", "name": "内蒙古自治区"},
{"code": "210000", "name": "辽宁省"},
{"code": "220000", "name": "吉林省"},
{"code": "230000", "name": "黑龙江省"},
{"code": "310000", "name": "上海市"},
{"code": "320000", "name": "江苏省"},
{"code": "330000", "name": "浙江省"},
{"code": "340000", "name": "安徽省"},
{"code": "350000", "name": "福建省"},
{"code": "360000", "name": "江西省"},
{"code": "370000", "name": "山东省"},
{"code": "410000", "name": "河南省"},
{"code": "420000", "name": "湖北省"},
{"code": "430000", "name": "湖南省"},
{"code": "440000", "name": "广东省"},
{"code": "450000", "name": "广西壮族自治区"},
{"code": "460000", "name": "海南省"},
{"code": "500000", "name": "重庆市"},
{"code": "510000", "name": "四川省"},
{"code": "520000", "name": "贵州省"},
{"code": "530000", "name": "云南省"},
{"code": "540000", "name": "西藏自治区"},
{"code": "610000", "name": "陕西省"},
{"code": "620000", "name": "甘肃省"},
{"code": "630000", "name": "青海省"},
{"code": "640000", "name": "宁夏回族自治区"},
{"code": "650000", "name": "新疆维吾尔自治区"}
]
logger.info("真实市场数据爬虫初始化完成")
def start_crawling(self):
"""启动爬虫"""
if self.is_running:
logger.warning("爬虫已在运行中")
return
logger.info("启动市场数据爬虫...")
self.is_running = True
self.start_time = datetime.now()
self.crawled_count = 0
self.error_count = 0
# 启动爬虫线程
self.crawler_thread = threading.Thread(target=self._crawl_loop, daemon=True)
self.crawler_thread.start()
logger.info("市场数据爬虫已启动")
def stop_crawling(self):
"""停止爬虫"""
if not self.is_running:
logger.warning("爬虫未在运行")
return
logger.info("正在停止市场数据爬虫...")
self.is_running = False
if self.crawler_thread and self.crawler_thread.is_alive():
self.crawler_thread.join(timeout=10)
logger.info("市场数据爬虫已停止")
def _crawl_loop(self):
"""爬虫主循环"""
interval_minutes = self.config.get('interval_minutes', 30)
while self.is_running:
try:
logger.info("开始新一轮数据爬取...")
# 爬取所有省份的数据
all_data = self._crawl_all_provinces()
if all_data:
# 保存数据
saved_count = self.data_manager.save_data(all_data)
self.crawled_count += saved_count
logger.info(f"本轮爬取完成,获取 {len(all_data)} 条数据,已保存 {saved_count} 条")
else:
logger.warning("本轮爬取未获取到数据")
# 等待下一轮
if self.is_running:
logger.info(f"等待 {interval_minutes} 分钟后进行下一轮爬取...")
time.sleep(interval_minutes * 60)
except Exception as e:
logger.error(f"爬取过程出错: {e}")
self.error_count += 1
if self.is_running:
time.sleep(60) # 出错后等待1分钟再重试
def _crawl_all_provinces(self) -> List[Dict]:
"""爬取所有省份的数据"""
all_data = []
try:
# 爬取前5个省份的真实数据
sample_provinces = self.provinces[:5]
for province in sample_provinces:
try:
province_data = self._crawl_province_real(province)
if province_data:
all_data.extend(province_data)
logger.info(f"省份 {province['name']} 爬取完成,获取 {len(province_data)} 条数据")
else:
logger.warning(f"省份 {province['name']} 未获取到数据")
# 避免请求过快
time.sleep(3)
except Exception as e:
logger.error(f"省份 {province['name']} 爬取失败: {e}")
self.error_count += 1
continue
return all_data
except Exception as e:
logger.error(f"批量爬取失败: {e}")
return []
def _crawl_province_real(self, province: Dict[str, str]) -> List[Dict]:
"""爬取单个省份的真实数据"""
province_name = province['name']
province_code = province['code']
all_data = []
try:
logger.info(f"开始获取{province_name}的市场数据...")
# 第一步:获取该省份的所有市场
markets = self._get_province_markets(province_code)
if not markets:
logger.warning(f"省份 {province_name} 没有找到市场数据")
return []
logger.info(f"{province_name}共有 {len(markets)} 个市场")
# 第二步:获取每个市场的详细数据
for market in markets[:3]: # 限制每个省份最多3个市场,避免请求过多
market_id = market.get("marketId")
market_name = market.get("marketName")
if market_id and market_name:
try:
market_data = self._get_market_details(market_id, province_name, province_code)
if market_data:
all_data.extend(market_data)
logger.info(f"成功获取市场 {market_name} 的 {len(market_data)} 条数据")
# 市场间隔
time.sleep(2)
except Exception as e:
logger.error(f"获取市场 {market_name} 数据失败: {e}")
continue
return all_data
except Exception as e:
logger.error(f"爬取省份 {province_name} 失败: {e}")
return []
def _get_province_markets(self, province_code: str) -> List[Dict]:
"""获取省份的所有市场"""
try:
url = f"{self.base_url}/priceQuotationController/getTodayMarketByProvinceCode"
params = {"code": province_code}
response = self._make_request('POST', url, params=params)
if response and response.get("code") == 200:
return response.get("content", [])
return []
except Exception as e:
logger.error(f"获取省份 {province_code} 市场列表失败: {e}")
return []
def _get_market_details(self, market_id: str, province_name: str, province_code: str) -> List[Dict]:
"""获取市场的详细价格数据"""
try:
url = f"{self.base_url}/priceQuotationController/pageList"
# 构建请求体
payload = {
"marketId": market_id,
"pageNum": 1,
"pageSize": 20, # 限制每个市场的数据量
"order": "desc",
"key": "",
"varietyTypeId": "",
"varietyId": "",
"startDate": (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d"),
"endDate": datetime.now().strftime("%Y-%m-%d")
}
response = self._make_request('POST', url, json=payload)
if not response or response.get("code") != 200:
return []
content = response.get("content", {})
items = content.get("list", [])
processed_data = []
timestamp = datetime.now()
for item in items:
try:
processed_item = {
# 基本信息
"省份": province_name,
"市场名称": str(item.get("marketName", "")),
"品种名称": str(item.get("varietyName", "")),
# 价格信息
"最低价": float(item.get("minimumPrice", 0) or 0),
"平均价": float(item.get("middlePrice", 0) or 0),
"最高价": float(item.get("highestPrice", 0) or 0),
"单位": str(item.get("meteringUnit", "")),
# 时间信息
"交易日期": str(item.get("reportTime", "")),
"更新时间": timestamp.strftime("%Y-%m-%d %H:%M:%S"),
# 其他信息
"市场ID": str(market_id),
"品种ID": str(item.get("varietyId", "")),
"产地": str(item.get("producePlace", "")),
"交易量": float(item.get("tradingVolume", 0) or 0),
"品种类型": str(item.get("varietyTypeName", ""))
}
# 验证必要字段
if processed_item["市场名称"] and processed_item["品种名称"]:
processed_data.append(processed_item)
except Exception as e:
logger.error(f"处理市场数据项失败: {e}")
continue
return processed_data
except Exception as e:
logger.error(f"获取市场 {market_id} 详细数据失败: {e}")
return []
def _make_request(self, method: str, url: str, **kwargs) -> Optional[Dict]:
"""发送HTTP请求"""
for attempt in range(self.retry_times):
try:
# 设置默认参数
request_kwargs = {
'headers': self.headers,
'timeout': self.timeout,
'verify': False, # 禁用SSL验证
**kwargs
}
response = requests.request(method, url, **request_kwargs)
# 检查响应状态
if response.status_code != 200:
raise requests.exceptions.RequestException(f"HTTP {response.status_code}")
# 检查响应内容
if not response.content:
raise ValueError("Empty response received")
return response.json()
except requests.exceptions.RequestException as e:
logger.warning(f"请求失败 (尝试 {attempt + 1}/{self.retry_times}): {e}")
if attempt < self.retry_times - 1:
time.sleep(2 ** attempt) # 指数退避
else:
logger.error(f"请求最终失败: {url}")
return None
except json.JSONDecodeError as e:
logger.error(f"JSON解析失败: {e}")
return None
except Exception as e:
logger.error(f"请求出现未知错误: {e}")
return None
def get_status(self) -> Dict[str, Any]:
"""获取爬虫状态"""
status = {
'status': '运行中' if self.is_running else '已停止',
'is_running': self.is_running,
'start_time': self.start_time.isoformat() if self.start_time else None,
'running_time': str(datetime.now() - self.start_time) if self.start_time else None,
'crawled_count': self.crawled_count,
'error_count': self.error_count,
'config': self.config
}
return status
def update_config(self, new_config: Dict[str, Any]):
"""更新爬虫配置"""
try:
# 更新配置
for key, value in new_config.items():
if key in self.config:
self.config[key] = value
# 保存配置
config.set('crawler', self.config)
config.save_config()
logger.info(f"爬虫配置已更新: {new_config}")
except Exception as e:
logger.error(f"更新爬虫配置失败: {e}")
raise
def crawl_once(self) -> List[Dict]:
"""执行一次爬取(用于测试)"""
logger.info("执行单次数据爬取...")
try:
all_data = self._crawl_all_provinces()
if all_data:
saved_count = self.data_manager.save_data(all_data)
logger.info(f"单次爬取完成,获取 {len(all_data)} 条数据,已保存 {saved_count} 条")
else:
logger.warning("单次爬取未获取到数据")
return all_data
except Exception as e:
logger.error(f"单次爬取失败: {e}")
return []
# 全局爬虫实例
crawler = MarketCrawler()
def get_crawler():
"""获取爬虫实例"""
return crawler
|
2301_78526554/agricultural-platform
|
core/crawler.py
|
Python
|
unknown
| 15,837
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
数据管理器 - 负责CSV数据的存储、查询和管理
"""
import os
import pandas as pd
import json
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Any
from pathlib import Path
import logging
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class DataManager:
"""数据管理器 - 专注于CSV文件操作"""
def __init__(self, data_dir: str = "data"):
self.data_dir = Path(data_dir)
self.csv_file = self.data_dir / "market_prices.csv"
self.backup_dir = self.data_dir / "backups"
self.initialize()
def initialize(self):
"""初始化数据目录和文件"""
try:
# 创建数据目录
self.data_dir.mkdir(exist_ok=True)
self.backup_dir.mkdir(exist_ok=True)
# 如果CSV文件不存在,创建空文件
if not self.csv_file.exists():
self.create_empty_csv()
logger.info(f"数据管理器初始化完成,数据目录: {self.data_dir}")
except Exception as e:
logger.error(f"数据管理器初始化失败: {e}")
raise
def create_empty_csv(self):
"""创建空的CSV文件"""
columns = [
'省份', '市场名称', '品种名称', '最低价', '平均价', '最高价',
'单位', '交易日期', '更新时间', '保存时间'
]
df = pd.DataFrame(columns=columns)
df.to_csv(self.csv_file, index=False, encoding='utf-8-sig')
logger.info(f"创建空CSV文件: {self.csv_file}")
def save_data(self, data_list: List[Dict]) -> int:
"""保存数据到CSV文件"""
if not data_list:
logger.warning("没有数据需要保存")
return 0
try:
# 转换为DataFrame
df = pd.DataFrame(data_list)
# 添加保存时间戳
df['保存时间'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
# 标准化列名
df = self._standardize_columns(df)
# 如果CSV文件已存在,合并数据
if self.csv_file.exists() and self.csv_file.stat().st_size > 0:
existing_df = pd.read_csv(self.csv_file, encoding='utf-8-sig')
# 合并数据
combined_df = pd.concat([existing_df, df], ignore_index=True)
# 去重(基于关键字段)
if self._has_key_columns(combined_df):
combined_df = combined_df.drop_duplicates(
subset=['市场名称', '品种名称', '交易日期'],
keep='last'
)
df = combined_df
# 保存到CSV
df.to_csv(self.csv_file, index=False, encoding='utf-8-sig')
logger.info(f"成功保存 {len(data_list)} 条数据,CSV文件总记录数: {len(df)}")
# 创建备份
self._create_backup()
return len(data_list)
except Exception as e:
logger.error(f"保存数据失败: {e}")
raise
def _standardize_columns(self, df: pd.DataFrame) -> pd.DataFrame:
"""标准化列名"""
column_mapping = {
'province': '省份',
'market_name': '市场名称',
'variety_name': '品种名称',
'min_price': '最低价',
'avg_price': '平均价',
'max_price': '最高价',
'unit': '单位',
'trade_date': '交易日期',
'crawl_time': '更新时间'
}
# 重命名列
df = df.rename(columns=column_mapping)
# 确保必要的列存在
required_columns = ['省份', '市场名称', '品种名称', '最低价', '平均价', '最高价', '单位', '交易日期']
for col in required_columns:
if col not in df.columns:
df[col] = ''
return df
def _has_key_columns(self, df: pd.DataFrame) -> bool:
"""检查是否有关键列用于去重"""
key_columns = ['市场名称', '品种名称', '交易日期']
return all(col in df.columns for col in key_columns)
def search_data(self, province: Optional[str] = None, variety: Optional[str] = None,
market: Optional[str] = None, date_from: Optional[str] = None,
date_to: Optional[str] = None, limit: int = 100) -> List[Dict]:
"""搜索数据"""
try:
if not self.csv_file.exists():
return []
df = pd.read_csv(self.csv_file, encoding='utf-8-sig')
if df.empty:
return []
# 应用过滤条件
if province:
df = df[df['省份'].str.contains(province, na=False)]
if variety:
df = df[df['品种名称'].str.contains(variety, na=False)]
if market:
df = df[df['市场名称'].str.contains(market, na=False)]
if date_from:
df = df[df['交易日期'] >= date_from]
if date_to:
df = df[df['交易日期'] <= date_to]
# 排序和限制数量
if '交易日期' in df.columns:
df = df.sort_values('交易日期', ascending=False)
df = df.head(limit)
# 清理数据并转换为字典列表
df = df.fillna('') # 将NaN替换为空字符串
records = df.to_dict('records')
# 进一步清理数据,确保JSON序列化兼容
cleaned_records = []
for record in records:
cleaned_record = {}
for key, value in record.items():
if pd.isna(value):
cleaned_record[key] = ''
elif isinstance(value, float) and (pd.isna(value) or value == float('inf') or value == float('-inf')):
cleaned_record[key] = 0
else:
cleaned_record[key] = value
cleaned_records.append(cleaned_record)
return cleaned_records
except Exception as e:
logger.error(f"搜索数据失败: {e}")
return []
def get_latest_data(self, limit: int = 50) -> List[Dict]:
"""获取最新数据"""
try:
if not self.csv_file.exists():
return []
df = pd.read_csv(self.csv_file, encoding='utf-8-sig')
if df.empty:
return []
# 清理数据:处理NaN值
df = df.fillna('') # 将NaN替换为空字符串
# 按保存时间排序
if '保存时间' in df.columns:
df = df.sort_values('保存时间', ascending=False)
elif '交易日期' in df.columns:
df = df.sort_values('交易日期', ascending=False)
df = df.head(limit)
# 转换为字典并清理数值
records = df.to_dict('records')
# 进一步清理数据,确保JSON序列化兼容
cleaned_records = []
for record in records:
cleaned_record = {}
for key, value in record.items():
if pd.isna(value):
cleaned_record[key] = ''
elif isinstance(value, float) and (pd.isna(value) or value == float('inf') or value == float('-inf')):
cleaned_record[key] = 0
else:
cleaned_record[key] = value
cleaned_records.append(cleaned_record)
return cleaned_records
except Exception as e:
logger.error(f"获取最新数据失败: {e}")
return []
def get_statistics(self) -> Dict[str, Any]:
"""获取数据统计信息"""
try:
if not self.csv_file.exists():
return {
'total_records': 0,
'total_markets': 0,
'total_varieties': 0,
'total_provinces': 0,
'last_update': None
}
df = pd.read_csv(self.csv_file, encoding='utf-8-sig')
if df.empty:
return {
'total_records': 0,
'total_markets': 0,
'total_varieties': 0,
'total_provinces': 0,
'last_update': None
}
stats = {
'total_records': len(df),
'total_markets': df['市场名称'].nunique() if '市场名称' in df.columns else 0,
'total_varieties': df['品种名称'].nunique() if '品种名称' in df.columns else 0,
'total_provinces': df['省份'].nunique() if '省份' in df.columns else 0,
'last_update': df['保存时间'].max() if '保存时间' in df.columns else None
}
return stats
except Exception as e:
logger.error(f"获取统计信息失败: {e}")
return {
'total_records': 0,
'total_markets': 0,
'total_varieties': 0,
'total_provinces': 0,
'last_update': None
}
def get_provinces(self) -> List[str]:
"""获取省份列表"""
try:
if not self.csv_file.exists():
return []
df = pd.read_csv(self.csv_file, encoding='utf-8-sig')
if df.empty or '省份' not in df.columns:
return []
provinces = df['省份'].dropna().unique().tolist()
return sorted(provinces)
except Exception as e:
logger.error(f"获取省份列表失败: {e}")
return []
def get_varieties(self) -> List[str]:
"""获取品种列表"""
try:
if not self.csv_file.exists():
return []
df = pd.read_csv(self.csv_file, encoding='utf-8-sig')
if df.empty or '品种名称' not in df.columns:
return []
varieties = df['品种名称'].dropna().unique().tolist()
return sorted(varieties)
except Exception as e:
logger.error(f"获取品种列表失败: {e}")
return []
def get_markets(self) -> List[str]:
"""获取市场列表"""
try:
if not self.csv_file.exists():
return []
df = pd.read_csv(self.csv_file, encoding='utf-8-sig')
if df.empty or '市场名称' not in df.columns:
return []
markets = df['市场名称'].dropna().unique().tolist()
return sorted(markets)
except Exception as e:
logger.error(f"获取市场列表失败: {e}")
return []
def export_csv(self, province: Optional[str] = None, variety: Optional[str] = None,
market: Optional[str] = None, date_from: Optional[str] = None,
date_to: Optional[str] = None) -> str:
"""导出CSV文件"""
try:
# 搜索数据
data = self.search_data(
province=province,
variety=variety,
market=market,
date_from=date_from,
date_to=date_to,
limit=10000 # 导出时不限制数量
)
if not data:
raise ValueError("没有数据可导出")
# 创建导出文件
export_file = self.data_dir / f"export_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
df = pd.DataFrame(data)
df.to_csv(export_file, index=False, encoding='utf-8-sig')
logger.info(f"数据导出成功: {export_file}")
return str(export_file)
except Exception as e:
logger.error(f"导出数据失败: {e}")
raise
def _create_backup(self):
"""创建数据备份"""
try:
if not self.csv_file.exists():
return
backup_file = self.backup_dir / f"backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.csv"
# 复制文件
import shutil
shutil.copy2(self.csv_file, backup_file)
# 清理旧备份(保留最近10个)
self._cleanup_old_backups()
except Exception as e:
logger.error(f"创建备份失败: {e}")
def _cleanup_old_backups(self, keep_count: int = 10):
"""清理旧备份文件"""
try:
backup_files = list(self.backup_dir.glob("backup_*.csv"))
if len(backup_files) > keep_count:
# 按修改时间排序
backup_files.sort(key=lambda x: x.stat().st_mtime, reverse=True)
# 删除多余的备份
for backup_file in backup_files[keep_count:]:
backup_file.unlink()
logger.info(f"删除旧备份: {backup_file}")
except Exception as e:
logger.error(f"清理备份失败: {e}")
# 全局数据管理器实例
data_manager = DataManager()
def get_data_manager():
"""获取数据管理器实例"""
return data_manager
|
2301_78526554/agricultural-platform
|
core/data_manager.py
|
Python
|
unknown
| 14,273
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
报告数据分析器 - 从报告中提取关键数据指标
"""
import pandas as pd
import re
import json
from datetime import datetime
from typing import Dict, List, Optional, Any
import logging
logger = logging.getLogger(__name__)
class ReportAnalyzer:
"""报告数据分析器"""
def __init__(self, data_manager):
self.data_manager = data_manager
def extract_key_metrics(self, reports_df: pd.DataFrame) -> Dict[str, Any]:
"""从报告数据中提取关键指标"""
try:
if reports_df.empty:
return {}
# 按日期排序
reports_df = reports_df.sort_values('日报日期', ascending=True)
metrics = {
'price_index_trend': self._extract_price_index_trend(reports_df),
'category_price_trends': self._extract_category_price_trends(reports_df),
'key_products_trends': self._extract_key_products_trends(reports_df),
'market_summary': self._extract_market_summary(reports_df),
'volatility_analysis': self._extract_volatility_analysis(reports_df)
}
return metrics
except Exception as e:
logger.error(f"提取关键指标失败: {e}")
return {}
def _extract_price_index_trend(self, reports_df: pd.DataFrame) -> List[Dict]:
"""提取价格指数趋势"""
trend_data = []
for _, row in reports_df.iterrows():
try:
date = row.get('日报日期', '')
content = row.get('总体结论', '')
# 提取农产品批发价格200指数
price_index_match = re.search(r'"农产品批发价格200指数".*?(\d+\.?\d*)', content)
basket_index_match = re.search(r'"菜篮子"产品批发价格指数.*?(\d+\.?\d*)', content)
if price_index_match:
trend_data.append({
'date': date,
'price_index_200': float(price_index_match.group(1)),
'basket_index': float(basket_index_match.group(1)) if basket_index_match else None
})
except Exception as e:
logger.warning(f"解析价格指数失败: {e}")
continue
return trend_data
def _extract_category_price_trends(self, reports_df: pd.DataFrame) -> Dict[str, List[Dict]]:
"""提取各类别价格趋势"""
categories = {
'vegetables': [], # 蔬菜
'fruits': [], # 水果
'meat': [], # 畜产品
'aquatic': [] # 水产品
}
for _, row in reports_df.iterrows():
try:
date = row.get('日报日期', '')
# 蔬菜价格
veg_content = row.get('蔬菜结论', '')
veg_price_match = re.search(r'(\d+\.?\d*)元/公斤', veg_content)
veg_change_match = re.search(r'比.*?([上下]升|下降)(\d+\.?\d*)%', veg_content)
if veg_price_match:
change_rate = 0
if veg_change_match:
direction = veg_change_match.group(1)
rate = float(veg_change_match.group(2))
change_rate = rate if '上升' in direction else -rate
categories['vegetables'].append({
'date': date,
'avg_price': float(veg_price_match.group(1)),
'change_rate': change_rate
})
# 水果价格
fruit_content = row.get('水果结论', '')
fruit_price_match = re.search(r'(\d+\.?\d*)元/公斤', fruit_content)
fruit_change_match = re.search(r'比.*?([上下]升|下降)(\d+\.?\d*)%', fruit_content)
if fruit_price_match:
change_rate = 0
if fruit_change_match:
direction = fruit_change_match.group(1)
rate = float(fruit_change_match.group(2))
change_rate = rate if '上升' in direction else -rate
categories['fruits'].append({
'date': date,
'avg_price': float(fruit_price_match.group(1)),
'change_rate': change_rate
})
# 畜产品价格 - 提取猪肉价格作为代表
meat_content = row.get('畜产品结论', '')
pork_price_match = re.search(r'猪肉.*?(\d+\.?\d*)元/公斤', meat_content)
pork_change_match = re.search(r'猪肉.*?比.*?([上下]升|下降)(\d+\.?\d*)%', meat_content)
if pork_price_match:
change_rate = 0
if pork_change_match:
direction = pork_change_match.group(1)
rate = float(pork_change_match.group(2))
change_rate = rate if '上升' in direction else -rate
categories['meat'].append({
'date': date,
'avg_price': float(pork_price_match.group(1)),
'change_rate': change_rate,
'product': '猪肉'
})
except Exception as e:
logger.warning(f"解析类别价格趋势失败: {e}")
continue
return categories
def _extract_key_products_trends(self, reports_df: pd.DataFrame) -> Dict[str, List[Dict]]:
"""提取重点产品价格趋势"""
products = {}
for _, row in reports_df.iterrows():
try:
date = row.get('日报日期', '')
# 从畜产品结论中提取各种肉类价格
meat_content = row.get('畜产品结论', '')
# 猪肉
pork_match = re.search(r'猪肉.*?(\d+\.?\d*)元/公斤', meat_content)
if pork_match:
if '猪肉' not in products:
products['猪肉'] = []
products['猪肉'].append({
'date': date,
'price': float(pork_match.group(1)),
'unit': '元/公斤'
})
# 牛肉
beef_match = re.search(r'牛肉.*?(\d+\.?\d*)元/公斤', meat_content)
if beef_match:
if '牛肉' not in products:
products['牛肉'] = []
products['牛肉'].append({
'date': date,
'price': float(beef_match.group(1)),
'unit': '元/公斤'
})
# 鸡蛋
egg_match = re.search(r'鸡蛋.*?(\d+\.?\d*)元/公斤', meat_content)
if egg_match:
if '鸡蛋' not in products:
products['鸡蛋'] = []
products['鸡蛋'].append({
'date': date,
'price': float(egg_match.group(1)),
'unit': '元/公斤'
})
except Exception as e:
logger.warning(f"解析重点产品趋势失败: {e}")
continue
return products
def _extract_market_summary(self, reports_df: pd.DataFrame) -> Dict[str, Any]:
"""提取市场总结信息"""
try:
latest_report = reports_df.iloc[-1] if not reports_df.empty else None
if not latest_report:
return {}
summary = {
'latest_date': latest_report.get('日报日期', ''),
'total_reports': len(reports_df),
'date_range': {
'start': reports_df['日报日期'].min() if '日报日期' in reports_df.columns else '',
'end': reports_df['日报日期'].max() if '日报日期' in reports_df.columns else ''
},
'latest_conclusions': {
'overall': latest_report.get('总体结论', ''),
'vegetables': latest_report.get('蔬菜结论', ''),
'fruits': latest_report.get('水果结论', ''),
'meat': latest_report.get('畜产品结论', ''),
'aquatic': latest_report.get('水产品结论', '')
}
}
return summary
except Exception as e:
logger.error(f"提取市场总结失败: {e}")
return {}
def _extract_volatility_analysis(self, reports_df: pd.DataFrame) -> Dict[str, Any]:
"""提取价格波动分析"""
try:
volatility_data = {
'top_gainers': [],
'top_losers': [],
'volatility_summary': {}
}
for _, row in reports_df.iterrows():
try:
date = row.get('日报日期', '')
analysis_content = row.get('涨跌幅分析', '')
# 提取涨幅前五名
gainers_match = re.search(r'价格升幅前五名的是(.+?),幅度分别为(.+?);', analysis_content)
if gainers_match:
products = gainers_match.group(1).split('、')
rates = re.findall(r'(\d+\.?\d*)%', gainers_match.group(2))
for i, product in enumerate(products):
if i < len(rates):
volatility_data['top_gainers'].append({
'date': date,
'product': product,
'change_rate': float(rates[i])
})
# 提取跌幅前五名
losers_match = re.search(r'价格降幅前五名的是(.+?),幅度分别为(.+?)。', analysis_content)
if losers_match:
products = losers_match.group(1).split('、')
rates = re.findall(r'(\d+\.?\d*)%', losers_match.group(2))
for i, product in enumerate(products):
if i < len(rates):
volatility_data['top_losers'].append({
'date': date,
'product': product,
'change_rate': -float(rates[i]) # 负值表示下跌
})
except Exception as e:
logger.warning(f"解析波动分析失败: {e}")
continue
return volatility_data
except Exception as e:
logger.error(f"提取波动分析失败: {e}")
return {}
def get_dashboard_data(self) -> Dict[str, Any]:
"""获取仪表盘数据"""
try:
# 读取报告数据
reports_file = self.data_manager.data_dir / "analysis_reports.csv"
if not reports_file.exists():
return {"error": "报告数据文件不存在"}
reports_df = pd.read_csv(reports_file, encoding='utf-8-sig')
# 只处理日报数据
daily_reports = reports_df[reports_df['报告类型代码'] == 'daily_price_report'].copy()
if daily_reports.empty:
return {"error": "没有找到日报数据"}
# 提取关键指标
metrics = self.extract_key_metrics(daily_reports)
return {
"success": True,
"data": metrics,
"summary": {
"total_reports": len(daily_reports),
"date_range": {
"start": daily_reports['日报日期'].min() if '日报日期' in daily_reports.columns else '',
"end": daily_reports['日报日期'].max() if '日报日期' in daily_reports.columns else ''
}
}
}
except Exception as e:
logger.error(f"获取仪表盘数据失败: {e}")
return {"error": str(e)}
|
2301_78526554/agricultural-platform
|
core/report_analyzer.py
|
Python
|
unknown
| 13,169
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
农业部分析报告爬虫 - 负责从农业部网站爬取分析报告数据
基于 https://pfsc.agri.cn/#/analysisReport
"""
import requests
import json
import time
import threading
from datetime import datetime, timedelta
from typing import Dict, List, Optional, Any
import logging
import urllib3
from bs4 import BeautifulSoup
import re
from .config import config
from .data_manager import get_data_manager
# 禁用SSL警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class ReportCrawler:
"""农业部分析报告爬虫"""
def __init__(self):
self.config = config.get_report_crawler_config()
self.data_manager = get_data_manager()
self.is_running = False
self.crawler_thread = None
self.start_time = None
self.crawled_count = 0
self.error_count = 0
# 农业部分析报告API配置
self.base_url = "https://pfsc.agri.cn/api"
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Content-Type": "application/json;charset=UTF-8",
"Origin": "https://pfsc.agri.cn",
"Referer": "https://pfsc.agri.cn/",
"Connection": "keep-alive",
"sec-ch-ua": '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "Windows",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin"
}
self.timeout = self.config.get('timeout_seconds', 30)
self.retry_times = self.config.get('retry_times', 3)
# 报告类型配置 - 多种报告类型
self.report_types = [
{"id": "daily", "name": "农产品批发市场价格日报", "code": "daily_price_report", "api": "FarmDaily/list"},
{"id": "weekly", "name": "农产品批发市场价格周报", "code": "weekly_price_report", "api": "farmWeekly/pageList"},
{"id": "analysis", "name": "农业分析报告", "code": "analysis_report", "api": "portal-analysis-report/selectListByPage"}
]
logger.info("农业部分析报告爬虫初始化完成")
def start_crawling(self):
"""启动报告爬虫"""
if self.is_running:
logger.warning("报告爬虫已在运行中")
return
logger.info("启动农业部分析报告爬虫...")
self.is_running = True
self.start_time = datetime.now()
self.crawled_count = 0
self.error_count = 0
# 启动爬虫线程
self.crawler_thread = threading.Thread(target=self._crawl_loop, daemon=True)
self.crawler_thread.start()
logger.info("分析报告爬虫已启动")
def stop_crawling(self):
"""停止报告爬虫"""
if not self.is_running:
logger.warning("报告爬虫未在运行")
return
logger.info("正在停止分析报告爬虫...")
self.is_running = False
if self.crawler_thread and self.crawler_thread.is_alive():
self.crawler_thread.join(timeout=10)
logger.info("分析报告爬虫已停止")
def _crawl_loop(self):
"""爬虫主循环"""
interval_hours = self.config.get('report_interval_hours', 6) # 6小时爬取一次报告
while self.is_running:
try:
logger.info("开始新一轮分析报告爬取...")
# 爬取所有类型的报告
all_reports = self._crawl_all_reports()
if all_reports:
# 保存报告数据
saved_count = self._save_reports(all_reports)
self.crawled_count += saved_count
logger.info(f"本轮报告爬取完成,获取 {len(all_reports)} 篇报告,已保存 {saved_count} 篇")
else:
logger.warning("本轮报告爬取未获取到数据")
# 等待下一轮
if self.is_running:
logger.info(f"等待 {interval_hours} 小时后进行下一轮报告爬取...")
time.sleep(interval_hours * 3600)
except Exception as e:
logger.error(f"报告爬取过程出错: {e}")
self.error_count += 1
if self.is_running:
time.sleep(300) # 出错后等待5分钟再重试
def _crawl_all_reports(self) -> List[Dict]:
"""爬取所有类型的分析报告"""
all_reports = []
try:
for report_type in self.report_types:
try:
reports = self._crawl_report_type(report_type)
if reports:
all_reports.extend(reports)
logger.info(f"报告类型 {report_type['name']} 爬取完成,获取 {len(reports)} 篇报告")
else:
logger.warning(f"报告类型 {report_type['name']} 未获取到数据")
# 避免请求过快
time.sleep(3)
except Exception as e:
logger.error(f"报告类型 {report_type['name']} 爬取失败: {e}")
self.error_count += 1
continue
return all_reports
except Exception as e:
logger.error(f"批量爬取报告失败: {e}")
return []
def _crawl_report_type(self, report_type: Dict[str, str]) -> List[Dict]:
"""爬取特定类型的报告"""
try:
logger.info(f"开始获取{report_type['name']}...")
# 获取报告列表
reports_list = self._get_reports_list(report_type)
if not reports_list:
logger.warning(f"报告类型 {report_type['name']} 没有找到报告列表")
return []
logger.info(f"{report_type['name']}共有 {len(reports_list)} 篇报告")
# 处理所有爬取到的报告数据
detailed_reports = []
total_reports = len(reports_list)
for i, report in enumerate(reports_list, 1):
try:
report_detail = self._get_report_detail(report, report_type)
if report_detail:
detailed_reports.append(report_detail)
logger.info(f"成功处理报告 ({i}/{total_reports}): {report_detail.get('报告标题', '未知标题')}")
# 每处理10个报告休息一下,避免过快
if i % 10 == 0:
time.sleep(1)
except Exception as e:
logger.error(f"处理报告数据失败 ({i}/{total_reports}): {e}")
continue
logger.info(f"{report_type['name']} 处理完成,成功处理 {len(detailed_reports)}/{total_reports} 篇报告")
return detailed_reports
except Exception as e:
logger.error(f"爬取报告类型 {report_type['name']} 失败: {e}")
return []
def _get_reports_list(self, report_type: Dict[str, str]) -> List[Dict]:
"""获取报告列表 - 支持多种API端点,分页爬取直到结束"""
try:
api_endpoint = report_type.get("api", "FarmDaily/list")
url = f"{self.base_url}/{api_endpoint}"
all_reports = []
page_num = 1
page_size = 20 if api_endpoint == "FarmDaily/list" else 10
max_reports = self.config.get('max_reports_per_type', 1000)
full_crawl = self.config.get('full_crawl', True)
page_delay = self.config.get('page_delay_seconds', 2)
logger.info(f"开始分页爬取 {report_type['name']},完整爬取: {full_crawl},最大数量: {max_reports}...")
while True:
try:
# 根据不同API构建请求参数
if api_endpoint == "FarmDaily/list":
# 日报API - POST请求
payload = {"pageNum": page_num, "pageSize": page_size}
response = self._make_request('POST', url, json=payload)
elif api_endpoint == "farmWeekly/pageList":
# 周报API - GET请求
params = {"pageNum": page_num, "pageSize": page_size}
response = self._make_request('GET', url, params=params)
elif api_endpoint == "portal-analysis-report/selectListByPage":
# 分析报告API - GET请求
params = {"pageable": True, "pageSize": page_size, "pageNum": page_num}
response = self._make_request('GET', url, params=params)
else:
logger.warning(f"未知的API端点: {api_endpoint}")
break
if not response or response.get("code") != 200:
logger.warning(f"{report_type['name']} 第{page_num}页请求失败")
break
content = response.get("content", {})
# 处理不同API的响应格式
if api_endpoint == "FarmDaily/list":
reports_list = content.get("list", [])
total_pages = content.get("pages", 0)
elif api_endpoint == "farmWeekly/pageList":
reports_list = content.get("list", [])
total_pages = content.get("pages", 0)
elif api_endpoint == "portal-analysis-report/selectListByPage":
reports_list = content.get("list", [])
total_pages = content.get("pages", 0)
else:
reports_list = []
total_pages = 0
# 如果当前页没有数据,停止爬取
if not reports_list:
logger.info(f"{report_type['name']} 第{page_num}页无数据,爬取结束")
break
# 为每个报告添加类型信息
for report in reports_list:
report['report_type'] = report_type
all_reports.extend(reports_list)
logger.info(f"{report_type['name']} 第{page_num}页获取 {len(reports_list)} 篇报告,累计 {len(all_reports)} 篇")
# 检查是否达到最大数量限制
if len(all_reports) >= max_reports:
logger.info(f"{report_type['name']} 已达到最大爬取数量 {max_reports},停止爬取")
break
# 如果不是完整爬取模式,只爬取第一页
if not full_crawl:
logger.info(f"{report_type['name']} 非完整爬取模式,只爬取第一页")
break
# 如果已经是最后一页,停止爬取
if total_pages > 0 and page_num >= total_pages:
logger.info(f"{report_type['name']} 已爬取完所有 {total_pages} 页")
break
# 如果当前页数据少于页面大小,可能是最后一页
if len(reports_list) < page_size:
logger.info(f"{report_type['name']} 当前页数据不足,可能已到最后一页")
break
page_num += 1
# 避免请求过快
time.sleep(page_delay)
except Exception as e:
logger.error(f"{report_type['name']} 第{page_num}页爬取失败: {e}")
break
logger.info(f"成功获取 {report_type['name']} 报告列表,共 {len(all_reports)} 篇")
return all_reports
except Exception as e:
logger.error(f"获取报告列表失败: {e}")
return []
def _get_report_detail(self, report: Dict, report_type: Dict[str, str]) -> Optional[Dict]:
"""获取报告详细内容 - 支持多种报告类型"""
try:
timestamp = datetime.now()
api_endpoint = report_type.get("api", "FarmDaily/list")
if api_endpoint == "FarmDaily/list":
# 处理日报数据
return self._process_daily_report(report, report_type, timestamp)
elif api_endpoint == "farmWeekly/pageList":
# 处理周报数据
return self._process_weekly_report(report, report_type, timestamp)
elif api_endpoint == "portal-analysis-report/selectListByPage":
# 处理分析报告数据
return self._process_analysis_report(report, report_type, timestamp)
else:
logger.warning(f"未知的报告类型: {api_endpoint}")
return None
except Exception as e:
logger.error(f"处理报告数据失败: {e}")
return None
def _process_daily_report(self, report: Dict, report_type: Dict[str, str], timestamp: datetime) -> Dict:
"""处理日报数据"""
return {
# 基本信息
"报告ID": str(report.get("id", "")),
"报告标题": str(report.get("remark", "")),
"报告类型": report_type.get("name", ""),
"报告类型代码": report_type.get("code", ""),
# 内容信息
"总体结论": str(report.get("counclesion", "")),
"畜产品结论": str(report.get("animalConclusion", "")),
"水产品结论": str(report.get("aquaticConclusion", "")),
"蔬菜结论": str(report.get("vegetablesConclusion", "")),
"水果结论": str(report.get("fruitsConclusion", "")),
"价格指数结论": str(report.get("indexConclusion", "")),
"涨跌幅分析": str(report.get("incOrReduRange", "")),
# 完整内容
"报告内容": self._clean_html_content(report.get("countent", "")),
"纯文本内容": str(report.get("countentstr", "")),
# 时间信息
"日报日期": str(report.get("daylyDate", "")),
"创建时间": str(report.get("createDate", "")),
"爬取时间": timestamp.strftime("%Y-%m-%d %H:%M:%S"),
# 其他信息
"来源": str(report.get("source", "")),
"年份": str(report.get("year", "")),
# 结构化数据
"JSON数据": str(report.get("wordJson", "")),
# 分类信息
"数据类型": "价格监测",
"监测范围": "全国农产品批发市场"
}
def _process_weekly_report(self, report: Dict, report_type: Dict[str, str], timestamp: datetime) -> Dict:
"""处理周报数据"""
return {
# 基本信息
"报告ID": str(report.get("id", "")),
"报告标题": str(report.get("title", "") or report.get("remark", "")),
"报告类型": report_type.get("name", ""),
"报告类型代码": report_type.get("code", ""),
# 内容信息
"报告摘要": str(report.get("summary", "")),
"报告内容": self._clean_html_content(report.get("content", "")),
"关键词": str(report.get("keywords", "")),
# 时间信息
"发布时间": str(report.get("publishTime", "")),
"创建时间": str(report.get("createTime", "")),
"爬取时间": timestamp.strftime("%Y-%m-%d %H:%M:%S"),
# 其他信息
"来源": str(report.get("source", "")),
"作者": str(report.get("author", "")),
"状态": str(report.get("status", "")),
# 分类信息
"数据类型": "周度分析",
"监测范围": "全国农产品市场"
}
def _process_analysis_report(self, report: Dict, report_type: Dict[str, str], timestamp: datetime) -> Dict:
"""处理分析报告数据"""
return {
# 基本信息
"报告ID": str(report.get("id", "")),
"报告标题": str(report.get("title", "")),
"报告类型": report_type.get("name", ""),
"报告类型代码": report_type.get("code", ""),
# 内容信息
"报告摘要": str(report.get("summary", "")),
"报告内容": self._clean_html_content(report.get("content", "")),
"关键词": str(report.get("keywords", "")),
# 时间信息
"发布时间": str(report.get("publishTime", "")),
"创建时间": str(report.get("createTime", "")),
"爬取时间": timestamp.strftime("%Y-%m-%d %H:%M:%S"),
# 其他信息
"来源": str(report.get("source", "")),
"作者": str(report.get("author", "")),
"阅读量": int(report.get("readCount", 0) or 0),
# 分类信息
"数据类型": "深度分析",
"分析领域": str(report.get("category", ""))
}
def _clean_html_content(self, html_content: str) -> str:
"""清理HTML内容,提取纯文本"""
try:
if not html_content:
return ""
# 使用BeautifulSoup解析HTML
soup = BeautifulSoup(html_content, 'html.parser')
# 移除脚本和样式标签
for script in soup(["script", "style"]):
script.decompose()
# 获取纯文本
text = soup.get_text()
# 清理多余的空白字符
text = re.sub(r'\s+', ' ', text).strip()
# 限制长度
if len(text) > 5000:
text = text[:5000] + "..."
return text
except Exception as e:
logger.error(f"清理HTML内容失败: {e}")
return str(html_content)[:1000] if html_content else ""
def _save_reports(self, reports: List[Dict]) -> int:
"""保存报告数据到CSV文件"""
try:
if not reports:
return 0
# 创建报告专用的CSV文件
reports_file = self.data_manager.data_dir / "analysis_reports.csv"
import pandas as pd
# 转换为DataFrame
df = pd.DataFrame(reports)
# 如果文件已存在,合并数据
if reports_file.exists() and reports_file.stat().st_size > 0:
existing_df = pd.read_csv(reports_file, encoding='utf-8-sig')
# 合并数据
combined_df = pd.concat([existing_df, df], ignore_index=True)
# 去重(基于报告ID)
if '报告ID' in combined_df.columns:
combined_df = combined_df.drop_duplicates(subset=['报告ID'], keep='last')
df = combined_df
# 保存到CSV
df.to_csv(reports_file, index=False, encoding='utf-8-sig')
logger.info(f"成功保存 {len(reports)} 篇报告,CSV文件总记录数: {len(df)}")
return len(reports)
except Exception as e:
logger.error(f"保存报告数据失败: {e}")
return 0
def _make_request(self, method: str, url: str, **kwargs) -> Optional[Dict]:
"""发送HTTP请求"""
for attempt in range(self.retry_times):
try:
# 设置默认参数
request_kwargs = {
'headers': self.headers,
'timeout': self.timeout,
'verify': False, # 禁用SSL验证
**kwargs
}
response = requests.request(method, url, **request_kwargs)
# 检查响应状态
if response.status_code != 200:
raise requests.exceptions.RequestException(f"HTTP {response.status_code}")
# 检查响应内容
if not response.content:
raise ValueError("Empty response received")
return response.json()
except requests.exceptions.RequestException as e:
logger.warning(f"请求失败 (尝试 {attempt + 1}/{self.retry_times}): {e}")
if attempt < self.retry_times - 1:
time.sleep(2 ** attempt) # 指数退避
else:
logger.error(f"请求最终失败: {url}")
return None
except json.JSONDecodeError as e:
logger.error(f"JSON解析失败: {e}")
return None
except Exception as e:
logger.error(f"请求出现未知错误: {e}")
return None
def get_status(self) -> Dict[str, Any]:
"""获取爬虫状态"""
status = {
'status': '运行中' if self.is_running else '已停止',
'is_running': self.is_running,
'start_time': self.start_time.isoformat() if self.start_time else None,
'running_time': str(datetime.now() - self.start_time) if self.start_time else None,
'crawled_count': self.crawled_count,
'error_count': self.error_count,
'report_types': len(self.report_types)
}
return status
def crawl_once(self) -> List[Dict]:
"""执行一次报告爬取(用于测试)"""
logger.info("执行单次报告爬取...")
try:
all_reports = self._crawl_all_reports()
if all_reports:
saved_count = self._save_reports(all_reports)
logger.info(f"单次报告爬取完成,获取 {len(all_reports)} 篇报告,已保存 {saved_count} 篇")
else:
logger.warning("单次报告爬取未获取到数据")
return all_reports
except Exception as e:
logger.error(f"单次报告爬取失败: {e}")
return []
# 全局报告爬虫实例
report_crawler = ReportCrawler()
def get_report_crawler():
"""获取报告爬虫实例"""
return report_crawler
|
2301_78526554/agricultural-platform
|
core/report_crawler.py
|
Python
|
unknown
| 23,475
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
任务调度器 - 负责定时任务的管理和执行
"""
import schedule
import threading
import time
from datetime import datetime, timedelta
from typing import Dict, Any
import logging
from .config import config
from .data_manager import get_data_manager
from .crawler import get_crawler
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class TaskScheduler:
"""任务调度器"""
def __init__(self):
self.config = config.get('scheduler', {})
self.data_manager = get_data_manager()
self.crawler = get_crawler()
self.is_running = False
self.scheduler_thread = None
self.start_time = None
# 任务统计
self.task_stats = {
'crawl_count': 0,
'cleanup_count': 0,
'backup_count': 0,
'last_crawl': None,
'last_cleanup': None,
'last_backup': None
}
logger.info("任务调度器初始化完成")
def start(self):
"""启动调度器"""
if self.is_running:
logger.warning("调度器已在运行中")
return
logger.info("启动任务调度器...")
self.is_running = True
self.start_time = datetime.now()
# 设置定时任务
self._setup_schedules()
# 启动调度器线程
self.scheduler_thread = threading.Thread(target=self._scheduler_loop, daemon=True)
self.scheduler_thread.start()
logger.info("任务调度器已启动")
def stop(self):
"""停止调度器"""
if not self.is_running:
logger.warning("调度器未在运行")
return
logger.info("正在停止任务调度器...")
self.is_running = False
# 清除所有定时任务
schedule.clear()
if self.scheduler_thread and self.scheduler_thread.is_alive():
self.scheduler_thread.join(timeout=5)
logger.info("任务调度器已停止")
def _setup_schedules(self):
"""设置定时任务"""
try:
# 清除现有任务
schedule.clear()
# 数据爬取任务(如果启用)
if config.get('crawler.enabled', True):
crawl_interval = config.get('crawler.interval_minutes', 30)
schedule.every(crawl_interval).minutes.do(self._scheduled_crawl)
logger.info(f"设置数据爬取任务: 每 {crawl_interval} 分钟执行一次")
# 数据清理任务
cleanup_interval = self.config.get('cleanup_interval_hours', 24)
schedule.every(cleanup_interval).hours.do(self._scheduled_cleanup)
logger.info(f"设置数据清理任务: 每 {cleanup_interval} 小时执行一次")
# 数据备份任务
backup_interval = self.config.get('backup_interval_hours', 6)
schedule.every(backup_interval).hours.do(self._scheduled_backup)
logger.info(f"设置数据备份任务: 每 {backup_interval} 小时执行一次")
except Exception as e:
logger.error(f"设置定时任务失败: {e}")
def _scheduler_loop(self):
"""调度器主循环"""
while self.is_running:
try:
schedule.run_pending()
time.sleep(1)
except Exception as e:
logger.error(f"调度器运行错误: {e}")
time.sleep(5)
def _scheduled_crawl(self):
"""定时数据爬取任务"""
try:
logger.info("执行定时数据爬取任务...")
# 检查爬虫是否已在运行
if self.crawler.is_running:
logger.info("爬虫已在运行中,跳过本次定时任务")
return
# 执行一次爬取
data = self.crawler.crawl_once()
# 更新统计
self.task_stats['crawl_count'] += 1
self.task_stats['last_crawl'] = datetime.now().isoformat()
logger.info(f"定时爬取任务完成,获取 {len(data) if data else 0} 条数据")
except Exception as e:
logger.error(f"定时爬取任务失败: {e}")
def _scheduled_cleanup(self):
"""定时数据清理任务"""
try:
logger.info("执行定时数据清理任务...")
# 更新统计
self.task_stats['cleanup_count'] += 1
self.task_stats['last_cleanup'] = datetime.now().isoformat()
logger.info("定时数据清理任务完成")
except Exception as e:
logger.error(f"定时数据清理任务失败: {e}")
def _scheduled_backup(self):
"""定时数据备份任务"""
try:
logger.info("执行定时数据备份任务...")
# 创建备份
self.data_manager._create_backup()
# 更新统计
self.task_stats['backup_count'] += 1
self.task_stats['last_backup'] = datetime.now().isoformat()
logger.info("定时数据备份任务完成")
except Exception as e:
logger.error(f"定时数据备份任务失败: {e}")
def get_status(self) -> Dict[str, Any]:
"""获取调度器状态"""
next_runs = {}
try:
# 获取下次运行时间
jobs = schedule.jobs
for job in jobs:
job_name = str(job.job_func).split()[1] if hasattr(job, 'job_func') else 'unknown'
next_run = job.next_run
if next_run:
next_runs[job_name] = next_run.isoformat()
except Exception as e:
logger.error(f"获取任务运行时间失败: {e}")
status = {
'is_running': self.is_running,
'start_time': self.start_time.isoformat() if self.start_time else None,
'running_time': str(datetime.now() - self.start_time) if self.start_time else None,
'task_count': len(schedule.jobs),
'task_stats': self.task_stats,
'next_runs': next_runs,
'config': self.config
}
return status
# 全局调度器实例
scheduler = TaskScheduler()
def get_scheduler():
"""获取调度器实例"""
return scheduler
|
2301_78526554/agricultural-platform
|
core/scheduler.py
|
Python
|
unknown
| 6,722
|
#!/bin/bash
# 华为云服务器部署脚本 - 农产品市场价格系统 + Odoo ERP
# Huawei Cloud Server Deployment Script
set -e # 遇到错误立即退出
echo "=== 华为云服务器部署开始 ==="
echo "系统信息: $(uname -a)"
echo "当前用户: $(whoami)"
echo "当前目录: $(pwd)"
echo "开始时间: $(date)"
# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color
# 日志函数
log_info() {
echo -e "${GREEN}[INFO]${NC} $1"
}
log_warn() {
echo -e "${YELLOW}[WARN]${NC} $1"
}
log_error() {
echo -e "${RED}[ERROR]${NC} $1"
}
# 检查系统环境
check_system() {
log_info "检查系统环境..."
# 检查Ubuntu版本
if [ -f /etc/os-release ]; then
. /etc/os-release
log_info "操作系统: $NAME $VERSION"
fi
# 检查内存
MEMORY=$(free -h | awk '/^Mem:/ {print $2}')
log_info "系统内存: $MEMORY"
# 检查磁盘空间
DISK=$(df -h / | awk 'NR==2 {print $4}')
log_info "可用磁盘空间: $DISK"
}
# 更新系统包
update_system() {
log_info "更新系统包..."
sudo apt update -y
sudo apt upgrade -y
sudo apt install -y curl wget git vim unzip software-properties-common
}
# 安装Docker
install_docker() {
log_info "安装Docker..."
if command -v docker &> /dev/null; then
log_info "Docker已安装: $(docker --version)"
return
fi
# 安装Docker
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
# 添加用户到docker组
sudo usermod -aG docker $USER
# 启动Docker服务
sudo systemctl start docker
sudo systemctl enable docker
log_info "Docker安装完成"
}
# 安装Docker Compose
install_docker_compose() {
log_info "安装Docker Compose..."
if command -v docker-compose &> /dev/null; then
log_info "Docker Compose已安装: $(docker-compose --version)"
return
fi
# 下载Docker Compose
sudo curl -L "https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
log_info "Docker Compose安装完成"
}
# 创建项目目录结构
create_project_structure() {
log_info "创建项目目录结构..."
# 创建主项目目录
mkdir -p ~/agricultural-platform
cd ~/agricultural-platform
# 创建子目录
mkdir -p {data,logs,config,backups,scripts}
mkdir -p odoo/{addons,config,data}
log_info "项目目录创建完成: $(pwd)"
}
# 创建Docker Compose配置
create_docker_compose() {
log_info "创建Docker Compose配置..."
cat > docker-compose.yml << 'EOF'
version: '3.8'
services:
# PostgreSQL数据库
postgres:
image: postgres:13
container_name: agricultural_postgres
environment:
POSTGRES_DB: postgres
POSTGRES_USER: odoo
POSTGRES_PASSWORD: odoo123
PGDATA: /var/lib/postgresql/data/pgdata
volumes:
- postgres_data:/var/lib/postgresql/data
ports:
- "5432:5432"
restart: unless-stopped
networks:
- agricultural_network
# Odoo ERP系统
odoo:
image: odoo:16.0
container_name: agricultural_odoo
depends_on:
- postgres
environment:
HOST: postgres
USER: odoo
PASSWORD: odoo123
ports:
- "8069:8069"
volumes:
- odoo_data:/var/lib/odoo
- ./odoo/addons:/mnt/extra-addons
- ./odoo/config:/etc/odoo
restart: unless-stopped
networks:
- agricultural_network
# 农产品价格API服务
price_api:
image: python:3.11-slim
container_name: agricultural_api
working_dir: /app
volumes:
- ./api:/app
- ./data:/app/data
- ./logs:/app/logs
ports:
- "8000:8000"
environment:
- PYTHONPATH=/app
command: >
bash -c "
pip install fastapi uvicorn pandas requests beautifulsoup4 schedule &&
python -m uvicorn main:app --host 0.0.0.0 --port 8000 --reload
"
restart: unless-stopped
networks:
- agricultural_network
# Nginx反向代理
nginx:
image: nginx:alpine
container_name: agricultural_nginx
ports:
- "80:80"
- "443:443"
volumes:
- ./nginx/nginx.conf:/etc/nginx/nginx.conf
- ./nginx/ssl:/etc/nginx/ssl
depends_on:
- odoo
- price_api
restart: unless-stopped
networks:
- agricultural_network
volumes:
postgres_data:
odoo_data:
networks:
agricultural_network:
driver: bridge
EOF
log_info "Docker Compose配置创建完成"
}
# 创建Nginx配置
create_nginx_config() {
log_info "创建Nginx配置..."
mkdir -p nginx
cat > nginx/nginx.conf << 'EOF'
events {
worker_connections 1024;
}
http {
upstream odoo {
server odoo:8069;
}
upstream api {
server price_api:8000;
}
server {
listen 80;
server_name _;
# Odoo ERP
location / {
proxy_pass http://odoo;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 价格API
location /api/ {
proxy_pass http://api/;
proxy_set_header Host $host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
}
# 静态文件
location /static/ {
proxy_pass http://api/static/;
}
}
}
EOF
log_info "Nginx配置创建完成"
}
# 创建Odoo配置
create_odoo_config() {
log_info "创建Odoo配置..."
cat > odoo/config/odoo.conf << 'EOF'
[options]
addons_path = /mnt/extra-addons,/usr/lib/python3/dist-packages/odoo/addons
data_dir = /var/lib/odoo
db_host = postgres
db_port = 5432
db_user = odoo
db_password = odoo123
admin_passwd = ZH3Y-6YB6-GAQV
logfile = /var/log/odoo/odoo.log
log_level = info
workers = 2
max_cron_threads = 1
EOF
log_info "Odoo配置创建完成"
}
# 下载项目代码
download_project_code() {
log_info "准备项目代码..."
# 创建API目录和基础文件
mkdir -p api/static/{css,js,html}
# 创建基础API文件
cat > api/main.py << 'EOF'
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
import pandas as pd
import os
from datetime import datetime
app = FastAPI(title="农产品市场价格API", version="1.0.0")
# 挂载静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")
@app.get("/")
async def root():
return {"message": "农产品市场价格管理系统", "version": "1.0.0", "status": "running"}
@app.get("/api/health")
async def health_check():
return {"status": "healthy", "timestamp": datetime.now().isoformat()}
@app.get("/api/prices")
async def get_prices():
try:
# 检查数据文件是否存在
data_file = "data/market_prices.csv"
if os.path.exists(data_file):
df = pd.read_csv(data_file)
return {
"success": True,
"data": df.to_dict('records'),
"count": len(df)
}
else:
return {
"success": True,
"data": [],
"count": 0,
"message": "暂无数据"
}
except Exception as e:
raise HTTPException(status_code=500, detail=str(e))
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)
EOF
# 创建示例数据
mkdir -p data
cat > data/market_prices.csv << 'EOF'
product_name,category,price,date,market,unit
白菜,vegetables,2.5,2025-01-25,北京新发地,公斤
苹果,fruits,8.0,2025-01-25,北京新发地,公斤
猪肉,meat,28.0,2025-01-25,北京新发地,公斤
带鱼,aquatic,35.0,2025-01-25,北京新发地,公斤
EOF
log_info "项目代码准备完成"
}
# 启动服务
start_services() {
log_info "启动服务..."
# 启动Docker服务
sudo systemctl start docker
# 构建并启动容器
docker-compose up -d
log_info "等待服务启动..."
sleep 30
# 检查服务状态
docker-compose ps
}
# 配置防火墙
configure_firewall() {
log_info "配置防火墙..."
# 检查ufw是否安装
if command -v ufw &> /dev/null; then
sudo ufw allow 22 # SSH
sudo ufw allow 80 # HTTP
sudo ufw allow 443 # HTTPS
sudo ufw allow 8000 # API
sudo ufw allow 8069 # Odoo
sudo ufw --force enable
log_info "防火墙配置完成"
else
log_warn "ufw未安装,跳过防火墙配置"
fi
}
# 创建管理脚本
create_management_scripts() {
log_info "创建管理脚本..."
# 创建启动脚本
cat > scripts/start.sh << 'EOF'
#!/bin/bash
cd ~/agricultural-platform
docker-compose up -d
echo "服务已启动"
docker-compose ps
EOF
# 创建停止脚本
cat > scripts/stop.sh << 'EOF'
#!/bin/bash
cd ~/agricultural-platform
docker-compose down
echo "服务已停止"
EOF
# 创建重启脚本
cat > scripts/restart.sh << 'EOF'
#!/bin/bash
cd ~/agricultural-platform
docker-compose down
docker-compose up -d
echo "服务已重启"
docker-compose ps
EOF
# 创建备份脚本
cat > scripts/backup.sh << 'EOF'
#!/bin/bash
BACKUP_DIR=~/agricultural-platform/backups
DATE=$(date +%Y%m%d_%H%M%S)
# 创建备份目录
mkdir -p $BACKUP_DIR
# 备份数据库
docker exec agricultural_postgres pg_dump -U odoo postgres > $BACKUP_DIR/db_backup_$DATE.sql
# 备份数据文件
tar -czf $BACKUP_DIR/data_backup_$DATE.tar.gz data/
echo "备份完成: $BACKUP_DIR"
ls -la $BACKUP_DIR/
EOF
# 给脚本执行权限
chmod +x scripts/*.sh
log_info "管理脚本创建完成"
}
# 显示部署信息
show_deployment_info() {
log_info "=== 部署完成 ==="
# 获取服务器IP
PUBLIC_IP=$(curl -s ifconfig.me 2>/dev/null || echo "获取IP失败")
PRIVATE_IP=$(hostname -I | awk '{print $1}')
echo ""
echo "🌐 访问地址:"
echo " Odoo ERP系统: http://$PUBLIC_IP (或 http://$PRIVATE_IP)"
echo " 价格API: http://$PUBLIC_IP:8000 (或 http://$PRIVATE_IP:8000)"
echo ""
echo "🔐 登录信息:"
echo " Odoo管理员: admin"
echo " Odoo密码: admin123"
echo " Odoo主密码: ZH3Y-6YB6-GAQV"
echo ""
echo "📁 项目目录: ~/agricultural-platform"
echo ""
echo "🛠️ 管理命令:"
echo " 启动服务: ~/agricultural-platform/scripts/start.sh"
echo " 停止服务: ~/agricultural-platform/scripts/stop.sh"
echo " 重启服务: ~/agricultural-platform/scripts/restart.sh"
echo " 数据备份: ~/agricultural-platform/scripts/backup.sh"
echo ""
echo "📊 服务状态:"
cd ~/agricultural-platform && docker-compose ps
}
# 主函数
main() {
log_info "开始华为云服务器部署..."
check_system
update_system
install_docker
install_docker_compose
create_project_structure
create_docker_compose
create_nginx_config
create_odoo_config
download_project_code
create_management_scripts
start_services
configure_firewall
show_deployment_info
log_info "部署完成!"
}
# 执行主函数
main
|
2301_78526554/agricultural-platform
|
huawei_cloud_deploy.sh
|
Shell
|
unknown
| 11,720
|
# **************************************************************************
# * *
# * 农产品市场数据爬虫 *
# * *
# * 作者: xiaohai *
# * 版本: v1.0.0 *
# * 日期: 2024-12-05 *
# * *
# * 功能: *
# * - 支持选择性爬取指定省份数据 *
# * - 支持CSV/JSON多种格式导出 *
# * - 自动保存历史数据并去重 *
# * - 支持断点续传和错误重试
# * *
# * 注意: *
# * - 由于数据来源的限制,部分数据可能无法获取 *
# * - 部分数据可能存在缺失或错误 *
# * - 请确保在合法合规的前提下使用本程序 *
# * *
# * 运行: *
# * - 命令行运行: python market_crawler.py *
# * - 选择性运行: python market_crawler.py -p 广东省 *
# * *
# * 导出: *
# * - CSV格式: python market_crawler.py -p 广东省 -o data.csv *
# * - JSON格式: python market_crawler.py -p 广东省 -o data.json *
# * - Excel格式: python market_crawler.py -p 广东省 -o data.xlsx
# * *
# * 文件夹格式: *
# * - market_crawler *
# * - 20xxxxxx *
# * - 市场1 *
# * - 市场2 *
# * -... *
# * - 20xxxxxx *
# * - 市场1 *
# * - 市场2 *
# * -... *
# * -... *
# * - merged *
# * - all_data_2024xxxx.csv *
# * - all_data_2024xxxx.json *
# - summary *
# * - summary_2024xxxx.csv *
# * - summary_2024xxxx.json *
# * - summary_2024xxxx.csv *
# * - summary_2024xxxx.json *
# * -... *
# * - market_crawler_log.txt *
# - market_crawler.py *
# * *
# * 断点续传: *
# * - 程序会自动保存历史数据,下次运行时会自动加载并去重 *
# * - 若需要重新开始,请删除历史数据文件 *
# * *
# **************************************************************************
import pkg_resources
import sys
import argparse
import subprocess
def check_and_install_packages():
"""检查并安装所需的包"""
required_packages = {
'requests': 'requests',
'pandas': 'pandas',
'beautifulsoup4': 'bs4',
'urllib3': 'urllib3',
'openpyxl': 'openpyxl', # Excel支持
'lxml': 'lxml', # XML解析器
'chardet': 'chardet', # 字符编码检测
'tqdm': 'tqdm', # 进度条
'colorama': 'colorama' # 控制台颜色
}
print("\n" + "="*50)
print("检查并安装依赖包...")
print("="*50)
try:
import colorama
colorama.init() # 初始化控制台颜色
success_mark = colorama.Fore.GREEN + "✓" + colorama.Style.RESET_ALL
error_mark = colorama.Fore.RED + "✗" + colorama.Style.RESET_ALL
except ImportError:
success_mark = "✓"
error_mark = "✗"
all_success = True
# 👇 镜像源配置(可更换为其他源)
mirror_url = "https://mirrors.aliyun.com/pypi/simple/"
trusted_hosts = [
"files.pythonhosted.org",
"pypi.org",
"mirrors.aliyun.com"
]
for package, import_name in required_packages.items():
try:
pkg_resources.require(package)
print(f"{success_mark} {package:15} 已安装")
except (pkg_resources.DistributionNotFound, pkg_resources.VersionConflict):
print(f"{error_mark} {package:15} 未安装,正在安装...")
try:
# 使用 pip 安装包,并指定镜像源和信任主机
subprocess.check_call([
sys.executable,
"-m",
"pip",
"install",
"--disable-pip-version-check", # 禁用pip版本检查
"--no-cache-dir", # 禁用缓存
"-i", mirror_url, # 指定镜像源
*[f"--trusted-host={host}" for host in trusted_hosts], # 添加信任的主机
package
], stdout=subprocess.DEVNULL)
print(f"{success_mark} {package:15} 安装成功")
except subprocess.CalledProcessError as e:
print(f"{error_mark} {package:15} 安装失败: {str(e)}")
all_success = False
except Exception as e:
print(f"{error_mark} {package:15} 安装出错: {str(e)}")
all_success = False
print("\n依赖包检查" + ("全部完成" if all_success else "存在问题"))
print("="*50 + "\n")
if not all_success:
print("某些依赖包安装失败,程序可能无法正常运行!")
if input("是否继续运行?(y/n): ").lower() != 'y':
sys.exit(1)
try:
# 检查并安装依赖包
check_and_install_packages()
# 导入所需的包
import requests
import pandas as pd
import logging
import time
from datetime import datetime, timedelta
import os
from typing import Dict, List
from bs4 import BeautifulSoup
import urllib3
import json
from tqdm import tqdm
import chardet
# 禁用SSL警告
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
except Exception as e:
print(f"\n程序初始化失败: {str(e)}")
sys.exit(1)
class MarketCrawler:
def __init__(self):
self.base_url = "https://pfsc.agri.cn/api"
self.headers = {
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
"Accept": "application/json, text/plain, */*",
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
"Content-Type": "application/json;charset=UTF-8",
"Origin": "https://pfsc.agri.cn",
"Referer": "https://pfsc.agri.cn/",
"Connection": "keep-alive",
"sec-ch-ua": '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
"sec-ch-ua-mobile": "?0",
"sec-ch-ua-platform": "Windows",
"sec-fetch-dest": "empty",
"sec-fetch-mode": "cors",
"sec-fetch-site": "same-origin"
}
# 修改数据保存目录为相对路径
script_dir = os.path.dirname(os.path.abspath(__file__))
self.data_dir = os.path.join(script_dir, "market_data")
os.makedirs(self.data_dir, exist_ok=True)
# 省份代码列表
self.provinces = [
{"code": "110000", "name": "北京市"},
{"code": "120000", "name": "天津市"},
{"code": "130000", "name": "河北省"},
{"code": "140000", "name": "山西省"},
{"code": "150000", "name": "内蒙古自治区"},
{"code": "210000", "name": "辽宁省"},
{"code": "220000", "name": "吉林省"},
{"code": "230000", "name": "黑龙江省"},
{"code": "310000", "name": "上海市"},
{"code": "320000", "name": "江苏省"},
{"code": "330000", "name": "浙江省"},
{"code": "340000", "name": "安徽省"},
{"code": "350000", "name": "福建省"},
{"code": "360000", "name": "江西省"},
{"code": "370000", "name": "山东省"},
{"code": "410000", "name": "河南省"},
{"code": "420000", "name": "湖北省"},
{"code": "430000", "name": "湖南省"},
{"code": "440000", "name": "广东省"},
{"code": "450000", "name": "广西壮族自治区"},
{"code": "460000", "name": "海南省"},
{"code": "500000", "name": "重庆市"},
{"code": "510000", "name": "四川省"},
{"code": "520000", "name": "贵州省"},
{"code": "530000", "name": "云南省"},
{"code": "540000", "name": "西藏自治区"},
{"code": "610000", "name": "陕西省"},
{"code": "620000", "name": "甘肃省"},
{"code": "630000", "name": "青海省"},
{"code": "640000", "name": "宁夏回族自治区"},
{"code": "650000", "name": "新疆维吾尔自治区"}
]
# 添加配置选项
self.config = {
"retry_times": 3,
"retry_delay": 5,
"export_format": "both", # 可选: "csv", "json", "both"
}
self.setup_logging()
def setup_logging(self):
# 确保日志文件保存在脚本所在目
script_dir = os.path.dirname(os.path.abspath(__file__))
log_file = os.path.join(script_dir, 'market_crawler.log')
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_file, encoding='utf-8'),
logging.StreamHandler()
]
)
self.logger = logging
def fetch_provinces(self) -> List[Dict]:
"""获取所有省份信息"""
try:
url = f"{self.base_url}/priceQuotationController/getProvinceList"
response = requests.get(
url,
headers=self.headers,
verify=False,
timeout=30
)
response.raise_for_status()
data = response.json()
if data.get("code") == 200:
return data.get("content", [])
return []
except Exception as e:
self.logger.error(f"获取省份列表失败: {str(e)}")
return []
def get_export_config(self):
"""获取导出配置"""
print("\n=== 导出配置 ===")
print("1. 仅导出CSV")
print("2. 仅导出JSON")
print("3. 两种格式都导出(认)")
while True:
choice = input("请选择导出格式 [1-3]: ").strip()
if not choice: # 默认两种都导出
return
try:
choice = int(choice)
if choice == 1:
self.config["export_format"] = "csv"
break
elif choice == 2:
self.config["export_format"] = "json"
break
elif choice == 3:
self.config["export_format"] = "both"
break
else:
print("请输入1-3之间的数字!")
except ValueError:
print("请输入有效的数字!")
print(f"\n已选择: {self.config['export_format'].upper()}")
def check_price_changed(self, market_name: str, new_data: List[Dict]) -> bool:
"""检查价格是否有变化"""
try:
market_dir = os.path.join(self.data_dir, market_name)
if not os.path.exists(market_dir):
return True # 目录不存在,说明是新市场
# 获取最新的CSV文件
csv_files = [f for f in os.listdir(market_dir) if f.endswith('.csv') and not f.endswith('_all.csv')]
if not csv_files:
return True # 没有历史文件,需要保存
latest_file = max(csv_files, key=lambda x: os.path.getctime(os.path.join(market_dir, x)))
latest_df = pd.read_csv(os.path.join(market_dir, latest_file))
# 确保数据格式一致
latest_df['交易日期'] = pd.to_datetime(latest_df['交易日期']).dt.date
new_df = pd.DataFrame(new_data)
new_df['交易日期'] = pd.to_datetime(new_df['交易日期']).dt.date
# 只比较今天的数据
today = datetime.now().date()
latest_today = latest_df[latest_df['交易日期'] == today]
new_today = new_df[new_df['交易日期'] == today]
if len(latest_today) == 0 or len(new_today) == 0:
return True # 任一方没有今天的数据,需要保存
# 比较关键字段是否有变化
price_columns = ['最低价', '平均价', '最高价']
for col in price_columns:
if not (latest_today[col] == new_today[col]).all():
return True # 价格有变化
self.logger.info(f"市场 {market_name} 价格无变化,跳过保存")
return False
except Exception as e:
self.logger.error(f"检查价格变化失败: {str(e)}")
return True # 出错时保险起见还是保存数据
def save_market_data(self, market_name: str, data: List[Dict]):
"""保存单个市场的数据"""
try:
if not data:
return
# 检查价格是否有变化
if not self.check_price_changed(market_name, data):
return
# 生成文件名和时间戳
timestamp = datetime.now()
date_str = timestamp.strftime("%Y%m%d")
# 为数据添加爬取时间
for item in data:
item['爬取时间'] = timestamp.strftime("%Y-%m-%d %H:%M:%S")
# 创建日期目录和市场目录
date_dir = os.path.join(self.data_dir, date_str)
safe_market_name = "".join(x for x in market_name if x.isalnum() or x in ['-', '_'])
market_dir = os.path.join(date_dir, safe_market_name)
os.makedirs(market_dir, exist_ok=True)
# 转换为DataFrame
new_df = pd.DataFrame(data)
# 根据配置保存数据
if self.config["export_format"] in ["json", "both"]:
json_file = os.path.join(market_dir, f"{safe_market_name}.json")
if os.path.exists(json_file):
# 如果文件存在,读取并合并数据
try:
with open(json_file, 'r', encoding='utf-8') as f:
existing_data = json.load(f)
if isinstance(existing_data, list):
# 合并数据并去重
all_data = existing_data + data
# 使用字典去重,保留最新的数据
unique_data = {}
for item in all_data:
key = (item['市场ID'], item['品种ID'], item['交易日期'])
unique_data[key] = item
data = list(unique_data.values())
except Exception as e:
self.logger.error(f"读取JSON文件失败: {str(e)}")
# 保存合并后的数据
with open(json_file, 'w', encoding='utf-8') as f:
json.dump(data, f, ensure_ascii=False, indent=2)
self.logger.info(f"JSON数据已更新到 {json_file}")
if self.config["export_format"] in ["csv", "both"]:
csv_file = os.path.join(market_dir, f"{safe_market_name}.csv")
if os.path.exists(csv_file):
# 如果文件存在,读取并合并数据
try:
existing_df = pd.read_csv(csv_file)
new_df = pd.concat([existing_df, new_df], ignore_index=True)
# 去重,保留最新的数据
new_df = new_df.sort_values('爬取时间').drop_duplicates(
subset=['市场ID', '品种ID', '交易日期'],
keep='last'
)
except Exception as e:
self.logger.error(f"读取CSV文件失败: {str(e)}")
# 保存合并后的数据
new_df = new_df.sort_values(['交易日期', '品种名称'])
new_df.to_csv(csv_file, index=False, encoding='utf-8-sig')
self.logger.info(f"CSV数据已更新到 {csv_file}")
# 更新汇总文件
summary_file = os.path.join(market_dir, f"{safe_market_name}_summary.csv")
try:
if os.path.exists(summary_file):
summary_df = pd.read_csv(summary_file)
summary_df = pd.concat([summary_df, new_df], ignore_index=True)
else:
summary_df = new_df.copy()
# 去重并排序
summary_df = summary_df.sort_values('爬取时间').drop_duplicates(
subset=['市场ID', '品种ID', '交易日期'],
keep='last'
)
summary_df = summary_df.sort_values(['交易日期', '品种名称'])
summary_df.to_csv(summary_file, index=False, encoding='utf-8-sig')
self.logger.info(f"汇总数据已更新到 {summary_file}")
except Exception as e:
self.logger.error(f"更新汇总文件失败: {str(e)}")
except Exception as e:
self.logger.error(f"保存市场 {market_name} 数据失败: {str(e)}")
raise
def fetch_market_details(self, market_id: str) -> List[Dict]:
"""获取单个市场的详细信息"""
max_retries = 3
retry_delay = 5
all_items = []
page_num = 1
timestamp = datetime.now()
while True:
for retry in range(max_retries):
try:
url = f"{self.base_url}/priceQuotationController/pageList"
# 构建请求体
payload = {
"marketId": market_id,
"pageNum": page_num,
"pageSize": 40,
"order": "desc",
"key": "",
"varietyTypeId": "",
"varietyId": "",
"startDate": (datetime.now() - timedelta(days=1)).strftime("%Y-%m-%d"),
"endDate": datetime.now().strftime("%Y-%m-%d")
}
# 发送请求
session = requests.Session()
response = session.post(
url,
headers=self.headers,
json=payload, # 使用json参数而不是data
verify=False,
timeout=30
)
# 检查响应状态
if response.status_code != 200:
raise requests.exceptions.RequestException(f"HTTP {response.status_code}")
# 检查响应内容
if not response.content:
raise ValueError("Empty response received")
data = response.json()
if data.get("code") == 200:
content = data.get("content", {})
items = content.get("list", [])
total = content.get("total", 0)
pages = content.get("pages", 1)
if items:
processed_items = []
for item in items:
try:
# 从返回的数据中获取省份信息
province_name = str(item.get("provinceName", ""))
province_code = str(item.get("provinceCode", ""))
processed_item = {
# 市场基本信息
"市场ID": str(market_id),
"市场代码": str(item.get("marketCode", "")),
"市场名称": str(item.get("marketName", "")),
"市场类型": str(item.get("marketType", "")),
# 品种信息
"品种ID": str(item.get("varietyId", "")),
"品种名称": str(item.get("varietyName", "")),
# 价格信息
"最低价": float(item.get("minimumPrice", 0) or 0),
"平均价": float(item.get("middlePrice", 0) or 0),
"最高价": float(item.get("highestPrice", 0) or 0),
"计量单位": str(item.get("meteringUnit", "")),
# 交易信息
"交易日期": str(item.get("reportTime", "")), # 使用reportTime作为交易日期
"交易量": float(item.get("tradingVolume", 0) or 0),
# 地理信息
"产地": str(item.get("producePlace", "")),
"销售地": str(item.get("salePlace", "")),
"省份": province_name,
"省份代码": province_code,
"地区名称": str(item.get("areaName", "")), # 添加地区信息
"地区代码": str(item.get("areaCode", "")),
# 其他信息
"品种类型": str(item.get("varietyTypeName", "")),
"品种类型ID": str(item.get("varietyTypeId", "")),
"入库时间": str(item.get("inStorageTime", "")),
"爬取时间": timestamp.strftime("%Y-%m-%d %H:%M:%S")
}
# 验证必要字段
if processed_item["市场名称"] and processed_item["交易日期"]:
processed_items.append(processed_item)
except Exception as e:
self.logger.error(f"处理数据项失败: {str(e)}, 数据: {item}")
continue
all_items.extend(processed_items)
self.logger.info(f"获取市场 {market_id} 第 {page_num}/{pages} 页数据,本页 {len(processed_items)} 条")
# 判断是否还有下一页
if page_num >= pages:
return all_items # 到达最后一页,返回所有数据
page_num += 1
time.sleep(1) # 翻页间隔
else:
return all_items # 没有数据了就返回
break # 成功获取数据后跳出重试循环
else:
error_msg = data.get("message", "Unknown error")
self.logger.error(f"API返回错误: {error_msg}")
if retry < max_retries - 1:
time.sleep(retry_delay)
continue
return all_items
except (requests.exceptions.RequestException, json.JSONDecodeError) as e:
self.logger.error(f"请求失败 (重试 {retry + 1}/{max_retries}): {str(e)}")
if retry < max_retries - 1:
time.sleep(retry_delay)
continue
return all_items
return all_items
def save_summary_data(self):
"""生成汇总数据"""
try:
print("\n=== 生成数据汇总 ===")
all_data = []
# 遍历日期目录
for date_dir in os.listdir(self.data_dir):
date_path = os.path.join(self.data_dir, date_dir)
if not os.path.isdir(date_path) or date_dir == 'summary':
continue
# 遍历市场目录
for market_dir in os.listdir(date_path):
market_path = os.path.join(date_path, market_dir)
if not os.path.isdir(market_path):
continue
# 读取该市场的所有CSV文件
csv_files = [f for f in os.listdir(market_path) if f.endswith('.csv')]
for csv_file in csv_files:
try:
df = pd.read_csv(os.path.join(market_path, csv_file))
all_data.append(df)
except Exception as e:
self.logger.error(f"读取文件 {csv_file} 失败: {str(e)}")
if all_data:
# 合并所有数据
summary_df = pd.concat(all_data, ignore_index=True)
# 确保日期格式正确
summary_df['交易日期'] = pd.to_datetime(summary_df['交易日期'])
summary_df['爬取时间'] = pd.to_datetime(summary_df['爬取时间'])
# 创建汇总目录
summary_dir = os.path.join(self.data_dir, 'summary')
os.makedirs(summary_dir, exist_ok=True)
# 按日期分组保存
for date, group in summary_df.groupby(summary_df['交易日期'].dt.date):
date_str = date.strftime('%Y%m%d')
# 保存CSV
csv_file = os.path.join(summary_dir, f'summary_{date_str}.csv')
group.to_csv(csv_file, index=False, encoding='utf-8-sig')
print(f"✓ 已生成 {date_str} 的CSV汇总数据")
# 保存JSON
json_file = os.path.join(summary_dir, f'summary_{date_str}.json')
group.to_json(json_file, orient='records', force_ascii=False, indent=2)
print(f"✓ 已生成 {date_str} 的JSON汇总数据")
# 生成完整汇总
summary_df = summary_df.sort_values(['交易日期', '省份', '市场名称', '品种名称'])
# 保存完整汇总文件
all_csv = os.path.join(summary_dir, 'summary_all.csv')
summary_df.to_csv(all_csv, index=False, encoding='utf-8-sig')
print(f"\n✓ 生成完整汇总CSV: {all_csv}")
all_json = os.path.join(summary_dir, 'summary_all.json')
summary_df.to_json(all_json, orient='records', force_ascii=False, indent=2)
print(f"✓ 已生成完整汇总JSON: {all_json}")
# 打印统计信息
print("\n=== 数据统计 ===")
print(f"总记录数: {len(summary_df)}")
print(f"覆盖日期: {summary_df['交易日期'].min():%Y-%m-%d} 至 {summary_df['交易日期'].max():%Y-%m-%d}")
print(f"省份数量: {summary_df['省份'].nunique()}")
print(f"市场数量: {summary_df['市场名称'].nunique()}")
print(f"品种数量: {summary_df['品种名称'].nunique()}")
else:
print("没有找到可用的数据文件!")
except Exception as e:
self.logger.error(f"生成汇总数据失败: {str(e)}")
raise
def merge_json_files(self):
"""合并所有JSON文件到一个总文件"""
try:
print("\n=== 合并JSON文件 ===")
all_data = []
# 遍历日期目录
for date_dir in os.listdir(self.data_dir):
date_path = os.path.join(self.data_dir, date_dir)
if not os.path.isdir(date_path):
continue
# 遍历市场目录
for market_dir in os.listdir(date_path):
market_path = os.path.join(date_path, market_dir)
if not os.path.isdir(market_path):
continue
# 获取所有JSON文件
json_files = [f for f in os.listdir(market_path) if f.endswith('.json')]
for json_file in json_files:
try:
with open(os.path.join(market_path, json_file), 'r', encoding='utf-8') as f:
data = json.load(f)
if isinstance(data, list):
all_data.extend(data)
else:
all_data.append(data)
except Exception as e:
self.logger.error(f"读取JSON文件 {json_file} 失: {str(e)}")
if all_data:
# 按日期排序
all_data.sort(key=lambda x: (x.get('交易日期', ''), x.get('省份', ''), x.get('市场名称', '')))
# 创建merged目录
merged_dir = os.path.join(self.data_dir, 'merged')
os.makedirs(merged_dir, exist_ok=True)
# 保存合并后的JSON文件
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
merged_file = os.path.join(merged_dir, f'all_markets_{timestamp}.json')
with open(merged_file, 'w', encoding='utf-8') as f:
json.dump(all_data, f, ensure_ascii=False, indent=2)
print(f"\n✓ 已生成合并JSON文件: {merged_file}")
print(f" - 记录数: {len(all_data)}")
print(f" - 市场数量: {len(set(item.get('市场名称', '') for item in all_data))}")
print(f" - 省份数量: {len(set(item.get('省份', '') for item in all_data))}")
# 同时生成CSV版本
df = pd.DataFrame(all_data)
csv_file = merged_file.replace('.json', '.csv')
df.to_csv(csv_file, index=False, encoding='utf-8-sig')
print(f"✓ 已生成合并CSV文件: {csv_file}")
else:
print("没有找到可用的JSON文件!")
except Exception as e:
self.logger.error(f"合并JSON文件失败: {str(e)}")
raise
def run(self, interval_minutes: int = 30):
"""运行爬虫,定期获取数据"""
self.logger.info("开始运行市场数据爬虫...")
# 获取导出配置
self.get_export_config()
# 询问是否需要合并历史JSON文件
merge_choice = input("\n是否合并历史JSON文件?(y/n,默认n): ").strip().lower()
if merge_choice == 'y':
self.merge_json_files()
if input("\n是否继续爬取新数据?(y/n,默认y): ").strip().lower() == 'n':
return
# 显示所有可选省份
print("\n=== 省份选择 ===")
for i, province in enumerate(self.provinces, 1):
print(f"{i}. {province['name']}")
# 获取用户输入
while True:
try:
choices = input("\n请输入要爬取的省份序号(多个省份用号分隔,直接回车爬取所有省份): ").strip()
if not choices: # 直接回车,爬取所有省份
selected_provinces = self.provinces
break
# 解析用户输
indices = [int(x.strip()) for x in choices.split(",")]
# 验证输入的序号是否有效
if all(1 <= i <= len(self.provinces) for i in indices):
selected_provinces = [self.provinces[i-1] for i in indices]
break
else:
print("输入序号无效,请重新输入!")
except ValueError:
print("输格式错误,请输入数字序号,多个序号用逗号分隔!")
# 显示选择的省份
print("\n已选择以下省份:")
for province in selected_provinces:
print(f"- {province['name']}")
while True:
try:
data_changed = False # 标记是否有数据变化
# 遍历选定的省份
for province in selected_provinces:
province_code = province["code"]
province_name = province["name"]
self.logger.info(f"开始获取{province_name}的市场数据...")
# 获取该省份的所有市场
url = f"{self.base_url}/priceQuotationController/getTodayMarketByProvinceCode"
params = {"code": province_code}
response = requests.post(
url,
headers=self.headers,
params=params,
verify=False,
timeout=30
)
response.raise_for_status()
data = response.json()
if data["code"] == 200 and "content" in data:
markets = data["content"]
self.logger.info(f"{province_name}共有 {len(markets)} 个市场")
for market in markets:
market_id = market.get("marketId")
market_name = market.get("marketName")
if market_id and market_name:
details = self.fetch_market_details(market_id)
if details:
# 添加省份信息
for detail in details:
detail["省份"] = province_name
detail["省份代码"] = province_code
# 保存该市场数据(如果有变化)
if self.check_price_changed(market_name, details):
self.save_market_data(market_name, details)
self.logger.info(f"成功获取并保存 {market_name} 的 {len(details)} 条数据")
data_changed = True
time.sleep(2)
# 处理一个省份后稍作等待
time.sleep(5)
# 只有在数据有变化时才生成汇总
if data_changed:
self.save_summary_data()
else:
self.logger.info("本轮所有市场价格无变化")
self.logger.info(f"本轮数据获取完成,等待 {interval_minutes} 分钟后进行下一次获取...")
time.sleep(interval_minutes * 60)
except Exception as e:
self.logger.error(f"运行出错: {str(e)}")
time.sleep(60)
def api_mode():
"""API模式下的数据获取"""
crawler = MarketCrawler()
data = []
try:
# 获取最新的市场数据
for province in crawler.provinces:
province_code = province["code"]
markets = crawler.fetch_market_details(province_code)
if markets:
data.extend(markets)
# 输出JSON格式数据
print(json.dumps(data, ensure_ascii=False))
return 0
except Exception as e:
print(json.dumps({
"error": str(e)
}, ensure_ascii=False))
return 1
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--mode', default='normal',
choices=['normal', 'api'],
help='运行模式: normal=普通模式, api=API模式')
args = parser.parse_args()
if args.mode == 'api':
sys.exit(api_mode())
else:
crawler = MarketCrawler()
crawler.run(interval_minutes=30)
# 最后一步,生成汇总数据
crawler.save_summary_data()
crawler.merge_json_files()
crawler.logger.info("数据爬取完成!")
|
2301_78526554/agricultural-platform
|
market_crawler.py
|
Python
|
unknown
| 41,071
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Odoo数据库迁移脚本 - 农产品市场价格系统
Odoo Database Migration Script for Agricultural Market Price System
"""
import os
import json
import logging
import pandas as pd
import xmlrpc.client
from datetime import datetime, timedelta
import sys
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('odoo_migration.log', encoding='utf-8'),
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
# Odoo配置信息
ODOO_CONFIG = {
'url': 'http://localhost:8069',
'database': 'agricultural_db', # 数据库名称
'username': 'admin',
'password': 'admin123',
'master_password': 'ZH3Y-6YB6-GAQV' # 您的Odoo主密码
}
# 保存配置到文件
def save_config():
"""保存配置信息到文件"""
config_file = 'odoo_config.json'
with open(config_file, 'w', encoding='utf-8') as f:
json.dump(ODOO_CONFIG, f, ensure_ascii=False, indent=2)
logger.info(f"配置已保存到: {config_file}")
class OdooMigrationTool:
def __init__(self):
self.config = ODOO_CONFIG
self.uid = None
self.models = None
self.common = None
def connect_odoo(self):
"""连接到Odoo服务器"""
try:
logger.info(f"连接Odoo服务器: {self.config['url']}")
self.common = xmlrpc.client.ServerProxy(f"{self.config['url']}/xmlrpc/2/common")
# 获取版本信息
version = self.common.version()
logger.info(f"Odoo版本: {version}")
# 用户认证
self.uid = self.common.authenticate(
self.config['database'],
self.config['username'],
self.config['password'],
{}
)
if not self.uid:
raise Exception("用户认证失败")
logger.info(f"认证成功,用户ID: {self.uid}")
self.models = xmlrpc.client.ServerProxy(f"{self.config['url']}/xmlrpc/2/object")
return True
except Exception as e:
logger.error(f"连接失败: {str(e)}")
return False
def check_database_exists(self):
"""检查数据库是否存在"""
try:
db_list = self.common.list()
if self.config['database'] in db_list:
logger.info(f"数据库 '{self.config['database']}' 已存在")
return True
else:
logger.warning(f"数据库 '{self.config['database']}' 不存在")
return False
except Exception as e:
logger.error(f"检查数据库失败: {str(e)}")
return False
def create_database(self):
"""创建新数据库"""
try:
logger.info(f"创建数据库: {self.config['database']}")
# 使用主密码创建数据库
result = self.common.create_database(
self.config['master_password'], # 主密码
self.config['database'], # 数据库名
True, # 演示数据
'zh_CN', # 语言
self.config['password'] # 管理员密码
)
if result:
logger.info("数据库创建成功")
return True
else:
logger.error("数据库创建失败")
return False
except Exception as e:
logger.error(f"创建数据库失败: {str(e)}")
return False
def install_modules(self):
"""安装必要的模块"""
required_modules = [
'sale_management', # 销售管理
'purchase', # 采购管理
'stock', # 库存管理
'account', # 会计
'product', # 产品管理
]
for module in required_modules:
try:
# 查找模块
module_ids = self.models.execute_kw(
self.config['database'], self.uid, self.config['password'],
'ir.module.module', 'search',
[[['name', '=', module]]]
)
if module_ids:
# 检查模块状态
module_info = self.models.execute_kw(
self.config['database'], self.uid, self.config['password'],
'ir.module.module', 'read',
[module_ids], {'fields': ['name', 'state']}
)
if module_info[0]['state'] != 'installed':
# 安装模块
self.models.execute_kw(
self.config['database'], self.uid, self.config['password'],
'ir.module.module', 'button_immediate_install',
[module_ids]
)
logger.info(f"模块 {module} 安装成功")
else:
logger.info(f"模块 {module} 已安装")
except Exception as e:
logger.error(f"安装模块 {module} 失败: {str(e)}")
def migrate_csv_data(self, csv_file):
"""迁移CSV数据到Odoo"""
if not os.path.exists(csv_file):
logger.error(f"CSV文件不存在: {csv_file}")
return False
try:
# 读取CSV数据
df = pd.read_csv(csv_file, encoding='utf-8')
logger.info(f"读取到 {len(df)} 条记录")
# 创建产品分类
categories = self.create_product_categories()
# 迁移产品数据
success_count = 0
error_count = 0
for index, row in df.iterrows():
try:
# 数据清理和映射
product_data = {
'name': str(row.get('product_name', f'产品_{index}')),
'list_price': float(row.get('price', row.get('avg_price', 0))),
'standard_price': float(row.get('price', row.get('avg_price', 0))),
'categ_id': categories.get(self.map_category(row.get('category', 'other')), 1),
'type': 'product',
'sale_ok': True,
'purchase_ok': True,
'active': True
}
# 检查产品是否已存在
existing = self.models.execute_kw(
self.config['database'], self.uid, self.config['password'],
'product.product', 'search',
[[['name', '=', product_data['name']]]]
)
if not existing:
# 创建产品
product_id = self.models.execute_kw(
self.config['database'], self.uid, self.config['password'],
'product.product', 'create',
[product_data]
)
success_count += 1
logger.info(f"创建产品: {product_data['name']} (ID: {product_id})")
else:
logger.info(f"产品已存在,跳过: {product_data['name']}")
except Exception as e:
error_count += 1
logger.error(f"处理第 {index} 行数据失败: {str(e)}")
logger.info(f"数据迁移完成 - 成功: {success_count}, 失败: {error_count}")
return True
except Exception as e:
logger.error(f"迁移CSV数据失败: {str(e)}")
return False
def create_product_categories(self):
"""创建产品分类"""
categories = {
'vegetable': '蔬菜类',
'fruit': '水果类',
'meat': '肉类',
'aquatic': '水产类',
'grain': '粮食类',
'other': '其他'
}
created_categories = {}
for code, name in categories.items():
try:
# 检查分类是否存在
existing = self.models.execute_kw(
self.config['database'], self.uid, self.config['password'],
'product.category', 'search',
[[['name', '=', name]]]
)
if existing:
created_categories[code] = existing[0]
logger.info(f"分类已存在: {name}")
else:
# 创建分类
cat_id = self.models.execute_kw(
self.config['database'], self.uid, self.config['password'],
'product.category', 'create',
[{'name': name}]
)
created_categories[code] = cat_id
logger.info(f"创建分类: {name} (ID: {cat_id})")
except Exception as e:
logger.error(f"创建分类 {name} 失败: {str(e)}")
return created_categories
def map_category(self, category):
"""映射产品分类"""
mapping = {
'vegetables': 'vegetable',
'fruits': 'fruit',
'meat': 'meat',
'aquatic': 'aquatic',
'grain': 'grain',
'蔬菜': 'vegetable',
'水果': 'fruit',
'肉类': 'meat',
'水产': 'aquatic',
'粮食': 'grain'
}
return mapping.get(str(category).lower(), 'other')
def export_migration_report(self):
"""导出迁移报告"""
try:
# 获取产品统计
products = self.models.execute_kw(
self.config['database'], self.uid, self.config['password'],
'product.product', 'search_count',
[[['active', '=', True]]]
)
# 获取分类统计
categories = self.models.execute_kw(
self.config['database'], self.uid, self.config['password'],
'product.category', 'search_count',
[[]]
)
report = {
'migration_date': datetime.now().isoformat(),
'database_name': self.config['database'],
'total_products': products,
'total_categories': categories,
'odoo_url': self.config['url'],
'status': 'completed'
}
with open('migration_report.json', 'w', encoding='utf-8') as f:
json.dump(report, f, ensure_ascii=False, indent=2)
logger.info("迁移报告已生成: migration_report.json")
return report
except Exception as e:
logger.error(f"生成迁移报告失败: {str(e)}")
return None
def main():
"""主函数"""
logger.info("=== 开始Odoo数据库迁移 ===")
# 保存配置
save_config()
# 创建迁移工具实例
migration_tool = OdooMigrationTool()
# 检查并创建数据库
if not migration_tool.check_database_exists():
logger.info("数据库不存在,将创建新数据库")
if not migration_tool.create_database():
logger.error("数据库创建失败,退出")
return False
# 连接Odoo
if not migration_tool.connect_odoo():
logger.error("无法连接到Odoo,退出")
return False
# 安装必要模块
migration_tool.install_modules()
# 迁移CSV数据
csv_files = [
'data/backups/backup_20250625_121804.csv',
'data/market_prices.csv'
]
for csv_file in csv_files:
if os.path.exists(csv_file):
logger.info(f"迁移文件: {csv_file}")
migration_tool.migrate_csv_data(csv_file)
break
else:
logger.warning("未找到CSV数据文件")
# 生成迁移报告
report = migration_tool.export_migration_report()
logger.info("=== 迁移完成 ===")
if report:
logger.info(f"数据库: {report['database_name']}")
logger.info(f"产品数量: {report['total_products']}")
logger.info(f"分类数量: {report['total_categories']}")
logger.info(f"访问地址: {report['odoo_url']}")
return True
if __name__ == "__main__":
main()
|
2301_78526554/agricultural-platform
|
odoo_database_migration.py
|
Python
|
unknown
| 13,196
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
农产品市场价格数据迁移到Odoo ERP系统
Migration script for Agricultural Market Price data to Odoo ERP
"""
import pandas as pd
import xmlrpc.client
import json
import logging
import sys
from datetime import datetime
import os
# 配置日志
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler('migration.log'),
logging.StreamHandler(sys.stdout)
]
)
logger = logging.getLogger(__name__)
class OdooMigration:
def __init__(self, config):
"""初始化Odoo连接配置"""
self.url = config['url']
self.db = config['database']
self.username = config['username']
self.password = config['password']
self.uid = None
self.models = None
self.common = None
def connect(self):
"""连接到Odoo服务器"""
try:
logger.info(f"正在连接到Odoo服务器: {self.url}")
self.common = xmlrpc.client.ServerProxy(f'{self.url}/xmlrpc/2/common')
# 验证服务器版本
version = self.common.version()
logger.info(f"Odoo服务器版本: {version}")
# 用户认证
self.uid = self.common.authenticate(self.db, self.username, self.password, {})
if not self.uid:
raise Exception("认证失败,请检查用户名和密码")
logger.info(f"用户认证成功,UID: {self.uid}")
self.models = xmlrpc.client.ServerProxy(f'{self.url}/xmlrpc/2/object')
return True
except Exception as e:
logger.error(f"连接Odoo失败: {str(e)}")
return False
def create_custom_module(self):
"""创建农产品市场价格自定义模块"""
logger.info("检查并创建自定义模块...")
# 检查模块是否存在
module_exists = self.models.execute_kw(
self.db, self.uid, self.password,
'ir.module.module', 'search',
[[['name', '=', 'agricultural_market']]]
)
if not module_exists:
logger.info("创建农产品市场价格模块...")
# 这里需要通过文件系统创建模块,暂时跳过
logger.warning("需要手动创建模块文件,请参考后续说明")
return True
def prepare_data(self, csv_file):
"""准备和清理CSV数据"""
logger.info(f"读取CSV文件: {csv_file}")
try:
# 读取CSV文件
df = pd.read_csv(csv_file, encoding='utf-8')
logger.info(f"成功读取 {len(df)} 条记录")
# 显示数据结构
logger.info("数据列名:")
for col in df.columns:
logger.info(f" - {col}")
# 数据清理和转换
cleaned_data = []
for index, row in df.iterrows():
try:
# 根据实际CSV结构调整字段映射
record = {
'name': str(row.get('product_name', row.get('name', f'产品_{index}'))),
'category': self.map_category(row.get('category', 'other')),
'price': float(row.get('price', row.get('avg_price', 0))),
'date': self.parse_date(row.get('date', row.get('report_date', datetime.now().strftime('%Y-%m-%d')))),
'market_location': str(row.get('market', row.get('location', '未知市场'))),
'unit': str(row.get('unit', '公斤')),
'source': str(row.get('source', '数据迁移')),
'active': True
}
cleaned_data.append(record)
except Exception as e:
logger.warning(f"处理第 {index} 行数据时出错: {str(e)}")
continue
logger.info(f"数据清理完成,有效记录: {len(cleaned_data)}")
return cleaned_data
except Exception as e:
logger.error(f"读取CSV文件失败: {str(e)}")
return []
def map_category(self, category):
"""映射产品分类"""
category_mapping = {
'vegetables': 'vegetable',
'fruits': 'fruit',
'meat': 'meat',
'aquatic': 'aquatic',
'grain': 'grain',
'蔬菜': 'vegetable',
'水果': 'fruit',
'肉类': 'meat',
'水产': 'aquatic',
'粮食': 'grain'
}
return category_mapping.get(str(category).lower(), 'other')
def parse_date(self, date_str):
"""解析日期字符串"""
try:
if pd.isna(date_str):
return datetime.now().strftime('%Y-%m-%d')
# 尝试多种日期格式
date_formats = ['%Y-%m-%d', '%Y/%m/%d', '%d/%m/%Y', '%d-%m-%Y']
for fmt in date_formats:
try:
return datetime.strptime(str(date_str), fmt).strftime('%Y-%m-%d')
except:
continue
return datetime.now().strftime('%Y-%m-%d')
except:
return datetime.now().strftime('%Y-%m-%d')
def create_product_categories(self):
"""创建产品分类"""
logger.info("创建产品分类...")
categories = [
{'name': '蔬菜类', 'code': 'vegetable'},
{'name': '水果类', 'code': 'fruit'},
{'name': '肉类', 'code': 'meat'},
{'name': '水产类', 'code': 'aquatic'},
{'name': '粮食类', 'code': 'grain'},
{'name': '其他', 'code': 'other'}
]
created_categories = {}
for cat in categories:
try:
# 检查分类是否已存在
existing = self.models.execute_kw(
self.db, self.uid, self.password,
'product.category', 'search',
[[['name', '=', cat['name']]]]
)
if existing:
created_categories[cat['code']] = existing[0]
logger.info(f"分类已存在: {cat['name']}")
else:
# 创建新分类
cat_id = self.models.execute_kw(
self.db, self.uid, self.password,
'product.category', 'create',
[{'name': cat['name']}]
)
created_categories[cat['code']] = cat_id
logger.info(f"创建分类: {cat['name']} (ID: {cat_id})")
except Exception as e:
logger.error(f"创建分类 {cat['name']} 失败: {str(e)}")
return created_categories
def migrate_products(self, data, categories):
"""迁移产品数据"""
logger.info("开始迁移产品数据...")
success_count = 0
error_count = 0
for record in data:
try:
# 检查产品是否已存在
existing = self.models.execute_kw(
self.db, self.uid, self.password,
'product.product', 'search',
[[['name', '=', record['name']]]]
)
if existing:
logger.info(f"产品已存在,跳过: {record['name']}")
continue
# 创建产品
product_data = {
'name': record['name'],
'categ_id': categories.get(record['category'], categories.get('other')),
'list_price': record['price'],
'standard_price': record['price'],
'type': 'product',
'sale_ok': True,
'purchase_ok': True,
'active': record['active']
}
product_id = self.models.execute_kw(
self.db, self.uid, self.password,
'product.product', 'create',
[product_data]
)
success_count += 1
logger.info(f"创建产品成功: {record['name']} (ID: {product_id})")
except Exception as e:
error_count += 1
logger.error(f"创建产品失败 {record['name']}: {str(e)}")
logger.info(f"产品迁移完成 - 成功: {success_count}, 失败: {error_count}")
return success_count, error_count
def main():
"""主函数"""
logger.info("=== 农产品市场价格数据迁移到Odoo开始 ===")
# Odoo连接配置
config = {
'url': 'http://localhost:8069', # 修改为您的Odoo服务器地址
'database': 'odoo', # 修改为您的数据库名
'username': 'admin', # 修改为您的用户名
'password': 'admin' # 修改为您的密码
}
# CSV文件路径
csv_file = 'data/backups/backup_20250625_121804.csv'
# 检查文件是否存在
if not os.path.exists(csv_file):
logger.error(f"CSV文件不存在: {csv_file}")
return False
# 创建迁移实例
migration = OdooMigration(config)
# 连接Odoo
if not migration.connect():
logger.error("无法连接到Odoo服务器")
return False
# 准备数据
data = migration.prepare_data(csv_file)
if not data:
logger.error("没有有效数据可迁移")
return False
# 创建产品分类
categories = migration.create_product_categories()
# 迁移产品数据
success, errors = migration.migrate_products(data, categories)
logger.info("=== 迁移完成 ===")
logger.info(f"总记录数: {len(data)}")
logger.info(f"成功迁移: {success}")
logger.info(f"失败记录: {errors}")
return True
if __name__ == "__main__":
main()
|
2301_78526554/agricultural-platform
|
odoo_migration.py
|
Python
|
unknown
| 10,477
|
# -*- coding: utf-8 -*-
"""
农产品市场价格Odoo模型文件
Agricultural Market Price Odoo Models
"""
# models/market_price.py
MARKET_PRICE_MODEL = '''# -*- coding: utf-8 -*-
from odoo import models, fields, api
from datetime import datetime, timedelta
class MarketPrice(models.Model):
_name = 'agricultural.market.price'
_description = '农产品市场价格'
_order = 'date desc, id desc'
_rec_name = 'product_name'
# 基本信息
product_name = fields.Char('产品名称', required=True, index=True)
product_id = fields.Many2one('product.product', '关联产品', ondelete='cascade')
category = fields.Selection([
('vegetable', '蔬菜类'),
('fruit', '水果类'),
('meat', '肉类'),
('aquatic', '水产类'),
('grain', '粮食类'),
('other', '其他')
], string='产品分类', required=True, default='other')
# 价格信息
price = fields.Float('价格(元/公斤)', digits=(10, 2), required=True)
unit = fields.Char('单位', default='公斤')
currency_id = fields.Many2one('res.currency', '货币', default=lambda self: self.env.company.currency_id)
# 时间和地点
date = fields.Date('价格日期', required=True, default=fields.Date.today)
market_location = fields.Char('市场地点', default='全国平均')
source = fields.Char('数据来源', default='市场调研')
# 价格变化
price_change = fields.Float('价格变化', compute='_compute_price_change', store=True)
price_change_percent = fields.Float('变化百分比(%)', compute='_compute_price_change', store=True)
# 状态
active = fields.Boolean('有效', default=True)
state = fields.Selection([
('draft', '草稿'),
('confirmed', '已确认'),
('archived', '已归档')
], string='状态', default='draft')
# 统计字段
avg_price_7d = fields.Float('7天平均价格', compute='_compute_avg_prices', store=True)
avg_price_30d = fields.Float('30天平均价格', compute='_compute_avg_prices', store=True)
@api.depends('product_name', 'date', 'price')
def _compute_price_change(self):
for record in self:
# 查找前一天的价格记录
previous_record = self.search([
('product_name', '=', record.product_name),
('date', '<', record.date),
('active', '=', True)
], limit=1, order='date desc')
if previous_record:
record.price_change = record.price - previous_record.price
if previous_record.price > 0:
record.price_change_percent = (record.price_change / previous_record.price) * 100
else:
record.price_change_percent = 0
else:
record.price_change = 0
record.price_change_percent = 0
@api.depends('product_name', 'date', 'price')
def _compute_avg_prices(self):
for record in self:
# 计算7天平均价格
date_7d_ago = record.date - timedelta(days=7)
records_7d = self.search([
('product_name', '=', record.product_name),
('date', '>=', date_7d_ago),
('date', '<=', record.date),
('active', '=', True)
])
record.avg_price_7d = sum(records_7d.mapped('price')) / len(records_7d) if records_7d else record.price
# 计算30天平均价格
date_30d_ago = record.date - timedelta(days=30)
records_30d = self.search([
('product_name', '=', record.product_name),
('date', '>=', date_30d_ago),
('date', '<=', record.date),
('active', '=', True)
])
record.avg_price_30d = sum(records_30d.mapped('price')) / len(records_30d) if records_30d else record.price
def action_confirm(self):
self.write({'state': 'confirmed'})
def action_archive(self):
self.write({'state': 'archived', 'active': False})
@api.model
def get_price_trend_data(self, product_name=None, days=30):
"""获取价格趋势数据"""
domain = [('active', '=', True)]
if product_name:
domain.append(('product_name', '=', product_name))
date_from = fields.Date.today() - timedelta(days=days)
domain.append(('date', '>=', date_from))
records = self.search(domain, order='date asc')
trend_data = []
for record in records:
trend_data.append({
'date': record.date.strftime('%Y-%m-%d'),
'product_name': record.product_name,
'price': record.price,
'category': record.category
})
return trend_data
'''
# models/product_category.py
PRODUCT_CATEGORY_MODEL = '''# -*- coding: utf-8 -*-
from odoo import models, fields, api
class ProductCategoryExtended(models.Model):
_inherit = 'product.category'
# 农产品特有字段
is_agricultural = fields.Boolean('农产品分类', default=False)
seasonal = fields.Boolean('季节性产品', default=False)
storage_days = fields.Integer('保存天数', default=7)
origin_region = fields.Char('主要产地')
# 价格统计
avg_price = fields.Float('平均价格', compute='_compute_price_stats', store=True)
price_volatility = fields.Float('价格波动率(%)', compute='_compute_price_stats', store=True)
@api.depends('product_ids.list_price')
def _compute_price_stats(self):
for category in self:
products = category.product_ids.filtered('active')
if products:
prices = products.mapped('list_price')
category.avg_price = sum(prices) / len(prices)
# 计算价格波动率
if len(prices) > 1:
import statistics
category.price_volatility = (statistics.stdev(prices) / category.avg_price) * 100 if category.avg_price > 0 else 0
else:
category.price_volatility = 0
else:
category.avg_price = 0
category.price_volatility = 0
'''
# views/market_price_views.xml
MARKET_PRICE_VIEWS = '''<?xml version="1.0" encoding="utf-8"?>
<odoo>
<!-- 市场价格列表视图 -->
<record id="view_market_price_tree" model="ir.ui.view">
<field name="name">agricultural.market.price.tree</field>
<field name="model">agricultural.market.price</field>
<field name="arch" type="xml">
<tree string="市场价格" decoration-success="price_change > 0" decoration-danger="price_change < 0">
<field name="date"/>
<field name="product_name"/>
<field name="category"/>
<field name="price"/>
<field name="unit"/>
<field name="price_change"/>
<field name="price_change_percent"/>
<field name="market_location"/>
<field name="state"/>
</tree>
</field>
</record>
<!-- 市场价格表单视图 -->
<record id="view_market_price_form" model="ir.ui.view">
<field name="name">agricultural.market.price.form</field>
<field name="model">agricultural.market.price</field>
<field name="arch" type="xml">
<form string="市场价格">
<header>
<button name="action_confirm" string="确认" type="object" class="oe_highlight" states="draft"/>
<button name="action_archive" string="归档" type="object" states="confirmed"/>
<field name="state" widget="statusbar" statusbar_visible="draft,confirmed,archived"/>
</header>
<sheet>
<group>
<group>
<field name="product_name"/>
<field name="category"/>
<field name="price"/>
<field name="unit"/>
</group>
<group>
<field name="date"/>
<field name="market_location"/>
<field name="source"/>
<field name="active"/>
</group>
</group>
<group string="价格变化">
<group>
<field name="price_change"/>
<field name="price_change_percent"/>
</group>
<group>
<field name="avg_price_7d"/>
<field name="avg_price_30d"/>
</group>
</group>
</sheet>
</form>
</field>
</record>
<!-- 搜索视图 -->
<record id="view_market_price_search" model="ir.ui.view">
<field name="name">agricultural.market.price.search</field>
<field name="model">agricultural.market.price</field>
<field name="arch" type="xml">
<search string="搜索市场价格">
<field name="product_name"/>
<field name="category"/>
<field name="market_location"/>
<filter string="今天" name="today" domain="[('date', '=', context_today().strftime('%Y-%m-%d'))]"/>
<filter string="本周" name="this_week" domain="[('date', '>=', (context_today() - datetime.timedelta(days=7)).strftime('%Y-%m-%d'))]"/>
<filter string="本月" name="this_month" domain="[('date', '>=', (context_today().replace(day=1)).strftime('%Y-%m-%d'))]"/>
<separator/>
<filter string="价格上涨" name="price_up" domain="[('price_change', '>', 0)]"/>
<filter string="价格下跌" name="price_down" domain="[('price_change', '<', 0)]"/>
<group expand="0" string="分组">
<filter string="产品分类" name="group_category" context="{'group_by': 'category'}"/>
<filter string="日期" name="group_date" context="{'group_by': 'date'}"/>
<filter string="市场地点" name="group_location" context="{'group_by': 'market_location'}"/>
</group>
</search>
</field>
</record>
<!-- 动作定义 -->
<record id="action_market_price" model="ir.actions.act_window">
<field name="name">市场价格</field>
<field name="res_model">agricultural.market.price</field>
<field name="view_mode">tree,form</field>
<field name="search_view_id" ref="view_market_price_search"/>
<field name="help" type="html">
<p class="o_view_nocontent_smiling_face">
创建第一个市场价格记录
</p>
<p>
在这里管理农产品的市场价格信息,跟踪价格变化趋势。
</p>
</field>
</record>
</odoo>
'''
def create_odoo_module_files():
"""创建Odoo模块文件"""
import os
# 创建目录结构
base_dir = "odoo-agricultural/addons/agricultural_market"
os.makedirs(f"{base_dir}/models", exist_ok=True)
os.makedirs(f"{base_dir}/views", exist_ok=True)
os.makedirs(f"{base_dir}/data", exist_ok=True)
os.makedirs(f"{base_dir}/security", exist_ok=True)
# 写入模型文件
with open(f"{base_dir}/models/market_price.py", 'w', encoding='utf-8') as f:
f.write(MARKET_PRICE_MODEL)
with open(f"{base_dir}/models/product_category.py", 'w', encoding='utf-8') as f:
f.write(PRODUCT_CATEGORY_MODEL)
# 写入视图文件
with open(f"{base_dir}/views/market_price_views.xml", 'w', encoding='utf-8') as f:
f.write(MARKET_PRICE_VIEWS)
print("Odoo模块文件创建完成!")
if __name__ == "__main__":
create_odoo_module_files()
|
2301_78526554/agricultural-platform
|
odoo_models.py
|
Python
|
unknown
| 12,286
|
#!/bin/bash
# Odoo ERP 部署脚本
# Agricultural Market Price System Migration to Odoo
echo "=== 农产品市场价格系统迁移到Odoo ERP ==="
# 检查Docker是否安装
if ! command -v docker &> /dev/null; then
echo "Docker未安装,正在安装..."
curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh
sudo usermod -aG docker $USER
echo "Docker安装完成,请重新登录后运行此脚本"
exit 1
fi
# 检查Docker Compose是否安装
if ! command -v docker-compose &> /dev/null; then
echo "Docker Compose未安装,正在安装..."
sudo curl -L "https://github.com/docker/compose/releases/download/v2.20.0/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
sudo chmod +x /usr/local/bin/docker-compose
fi
# 创建项目目录
mkdir -p odoo-agricultural
cd odoo-agricultural
# 创建docker-compose.yml文件
cat > docker-compose.yml << 'EOF'
version: '3.8'
services:
db:
image: postgres:13
environment:
POSTGRES_DB: postgres
POSTGRES_USER: odoo
POSTGRES_PASSWORD: odoo123
volumes:
- odoo-db-data:/var/lib/postgresql/data
ports:
- "5432:5432"
restart: unless-stopped
odoo:
image: odoo:16.0
depends_on:
- db
ports:
- "8069:8069"
environment:
HOST: db
USER: odoo
PASSWORD: odoo123
volumes:
- odoo-web-data:/var/lib/odoo
- ./config:/etc/odoo
- ./addons:/mnt/extra-addons
restart: unless-stopped
command: -- --dev=reload
volumes:
odoo-web-data:
odoo-db-data:
EOF
# 创建配置目录
mkdir -p config addons
# 创建Odoo配置文件
cat > config/odoo.conf << 'EOF'
[options]
addons_path = /mnt/extra-addons,/usr/lib/python3/dist-packages/odoo/addons
data_dir = /var/lib/odoo
db_host = db
db_port = 5432
db_user = odoo
db_password = odoo123
admin_passwd = admin123
logfile = /var/log/odoo/odoo.log
log_level = info
EOF
# 创建农产品管理模块目录结构
mkdir -p addons/agricultural_market/{models,views,data,security,static/description}
# 创建模块清单文件
cat > addons/agricultural_market/__manifest__.py << 'EOF'
{
'name': '农产品市场价格管理',
'version': '16.0.1.0.0',
'category': 'Sales',
'summary': 'Agricultural Market Price Management System',
'description': """
农产品市场价格管理系统
========================
功能包括:
* 农产品价格数据管理
* 市场价格趋势分析
* 价格波动监控
* 数据报表和仪表盘
""",
'author': 'Agricultural Platform Team',
'website': 'https://your-website.com',
'depends': ['base', 'product', 'sale', 'purchase', 'stock'],
'data': [
'security/ir.model.access.csv',
'views/market_price_views.xml',
'views/menu_views.xml',
'data/product_category_data.xml',
],
'demo': [],
'installable': True,
'auto_install': False,
'application': True,
}
EOF
# 创建模块初始化文件
cat > addons/agricultural_market/__init__.py << 'EOF'
from . import models
EOF
# 创建模型初始化文件
cat > addons/agricultural_market/models/__init__.py << 'EOF'
from . import market_price
from . import product_category
EOF
echo "正在启动Odoo服务..."
docker-compose up -d
echo "等待服务启动..."
sleep 30
echo "检查服务状态..."
docker-compose ps
echo ""
echo "=== 部署完成 ==="
echo "Odoo访问地址: http://localhost:8069"
echo "数据库名: odoo"
echo "管理员密码: admin123"
echo ""
echo "请等待约2-3分钟让服务完全启动,然后访问上述地址进行初始化设置"
echo ""
echo "下一步:"
echo "1. 访问 http://localhost:8069 创建数据库"
echo "2. 安装农产品管理模块"
echo "3. 运行数据迁移脚本: python3 odoo_migration.py"
|
2301_78526554/agricultural-platform
|
odoo_setup.sh
|
Shell
|
unknown
| 3,863
|
#!/bin/bash
# 农产品市场价格系统完整迁移脚本
# Complete Migration Script for Agricultural Market Price System
echo "=== 农产品市场价格系统迁移到Odoo ERP ==="
echo "开始时间: $(date)"
# 检查Python环境
if ! command -v python3 &> /dev/null; then
echo "Python3未安装,请先安装Python3"
exit 1
fi
# 安装Python依赖
echo "安装Python依赖包..."
pip3 install -r requirements_odoo.txt
# 给脚本执行权限
chmod +x odoo_setup.sh
# 运行Odoo部署脚本
echo "部署Odoo ERP系统..."
./odoo_setup.sh
# 等待Odoo服务启动
echo "等待Odoo服务完全启动..."
sleep 60
# 检查Odoo服务状态
echo "检查Odoo服务状态..."
if curl -f http://localhost:8069 > /dev/null 2>&1; then
echo "✅ Odoo服务启动成功"
else
echo "❌ Odoo服务启动失败,请检查日志"
docker-compose -f odoo-agricultural/docker-compose.yml logs
exit 1
fi
# 创建Odoo模块文件
echo "创建农产品管理模块..."
python3 odoo_models.py
# 提示用户进行手动配置
echo ""
echo "=== 下一步操作指南 ==="
echo "1. 访问 http://localhost:8069"
echo "2. 创建数据库:"
echo " - 数据库名: agricultural_db"
echo " - 邮箱: admin@example.com"
echo " - 密码: admin123"
echo " - 语言: 简体中文"
echo " - 国家: 中国"
echo ""
echo "3. 安装必要模块:"
echo " - Sales (销售)"
echo " - Purchase (采购)"
echo " - Inventory (库存)"
echo " - Accounting (会计)"
echo ""
echo "4. 安装农产品管理模块:"
echo " - 进入应用商店"
echo " - 搜索 '农产品市场价格管理'"
echo " - 点击安装"
echo ""
echo "5. 配置完成后运行数据迁移:"
echo " python3 odoo_migration.py"
echo ""
echo "完成以上步骤后,您的农产品数据将成功迁移到Odoo ERP系统中!"
echo ""
echo "如遇问题,请查看日志文件: migration.log"
|
2301_78526554/agricultural-platform
|
run_migration.sh
|
Shell
|
unknown
| 1,897
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
农产品市场价格管理平台启动脚本
"""
import uvicorn
import sys
import os
from pathlib import Path
# 添加项目根目录到Python路径
project_root = Path(__file__).parent
sys.path.insert(0, str(project_root))
def main():
"""主函数"""
print("🚀 启动农产品市场价格管理平台...")
print("=" * 50)
# 确保必要的目录存在
directories = ['data', 'logs', 'static/css', 'static/js']
for directory in directories:
Path(directory).mkdir(parents=True, exist_ok=True)
# 启动配置
config = {
"app": "app:app",
"host": "0.0.0.0",
"port": 8000,
"reload": True,
"log_level": "info",
"access_log": True
}
print(f"📊 管理界面: http://localhost:{config['port']}")
print(f"📖 API文档: http://localhost:{config['port']}/docs")
print("=" * 50)
try:
uvicorn.run(**config)
except KeyboardInterrupt:
print("\n🛑 平台已停止")
except Exception as e:
print(f"❌ 启动失败: {e}")
sys.exit(1)
if __name__ == "__main__":
main()
|
2301_78526554/agricultural-platform
|
start.py
|
Python
|
unknown
| 1,187
|
/* 全局样式 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
background: #f5f7fa;
min-height: 100vh;
color: #333;
line-height: 1.6;
margin: 0;
overflow-x: hidden;
}
#app {
display: flex;
min-height: 100vh;
}
/* 侧边栏样式 */
.sidebar {
width: 260px;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
position: fixed;
top: 0;
left: 0;
height: 100vh;
z-index: 1000;
transition: transform 0.3s ease;
overflow-y: auto;
}
.sidebar.collapsed {
transform: translateX(-100%);
}
.sidebar-header {
padding: 1.5rem;
border-bottom: 1px solid rgba(255, 255, 255, 0.1);
display: flex;
justify-content: space-between;
align-items: center;
}
.sidebar-header .logo {
display: flex;
align-items: center;
gap: 10px;
}
.sidebar-header .logo i {
font-size: 1.5rem;
}
.sidebar-header .logo h2 {
font-size: 1.2rem;
margin: 0;
font-weight: 600;
}
.sidebar-toggle {
background: none;
border: none;
color: white;
font-size: 1.2rem;
cursor: pointer;
padding: 5px;
border-radius: 4px;
transition: background-color 0.3s ease;
}
.sidebar-toggle:hover {
background-color: rgba(255, 255, 255, 0.1);
}
.mobile-toggle {
display: none;
}
.sidebar-nav {
padding: 1rem 0;
}
.nav-list {
list-style: none;
margin: 0;
padding: 0;
}
.nav-item {
margin: 0;
}
.nav-link {
display: flex;
align-items: center;
gap: 12px;
padding: 12px 1.5rem;
color: rgba(255, 255, 255, 0.8);
text-decoration: none;
transition: all 0.3s ease;
border-left: 3px solid transparent;
}
.nav-link:hover {
background-color: rgba(255, 255, 255, 0.1);
color: white;
}
.nav-link.active {
background-color: rgba(255, 255, 255, 0.15);
color: white;
border-left-color: white;
}
.nav-link i {
font-size: 1.1rem;
width: 20px;
text-align: center;
}
/* 主内容区域 */
.main-content {
flex: 1;
margin-left: 260px;
min-height: 100vh;
display: flex;
flex-direction: column;
transition: margin-left 0.3s ease;
}
.main-content.expanded {
margin-left: 0;
}
/* 顶部导航栏 */
.header {
background: white;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
position: sticky;
top: 0;
z-index: 100;
border-bottom: 1px solid #e1e5e9;
}
.header-content {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 1.5rem;
}
.header-title h1 {
font-size: 1.5rem;
color: #333;
font-weight: 600;
margin: 0;
}
.header-actions {
display: flex;
gap: 10px;
}
/* 内容包装器 */
.content-wrapper {
flex: 1;
padding: 1.5rem;
overflow-y: auto;
}
/* 内容区域 */
.content-section {
display: none;
}
.content-section.active {
display: block;
}
/* 快速操作 */
.quick-actions {
background: white;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
margin-top: 2rem;
overflow: hidden;
}
.action-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 1rem;
padding: 1.5rem;
}
.action-card {
background: linear-gradient(135deg, #f8f9fa 0%, #e9ecef 100%);
border: 2px solid transparent;
border-radius: 12px;
padding: 1.5rem;
text-align: center;
cursor: pointer;
transition: all 0.3s ease;
text-decoration: none;
color: #333;
}
.action-card:hover {
transform: translateY(-4px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.15);
border-color: #667eea;
}
.action-card i {
font-size: 2rem;
color: #667eea;
margin-bottom: 1rem;
}
.action-card h3 {
font-size: 1.1rem;
margin: 0.5rem 0;
color: #333;
}
.action-card p {
font-size: 0.9rem;
color: #666;
margin: 0;
}
/* 按钮样式 */
.btn {
padding: 10px 20px;
border: none;
border-radius: 8px;
font-size: 14px;
font-weight: 500;
cursor: pointer;
transition: all 0.3s ease;
display: inline-flex;
align-items: center;
gap: 8px;
text-decoration: none;
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.btn-primary {
background: #007bff;
color: white;
}
.btn-primary:hover {
background: #0056b3;
}
.btn-success {
background: #28a745;
color: white;
}
.btn-success:hover {
background: #1e7e34;
}
.btn-danger {
background: #dc3545;
color: white;
}
.btn-danger:hover {
background: #c82333;
}
.btn-info {
background: #17a2b8;
color: white;
}
.btn-info:hover {
background: #138496;
}
.btn-secondary {
background: #6c757d;
color: white;
}
.btn-secondary:hover {
background: #545b62;
}
/* 主要内容区域 */
.main {
padding: 2rem 0;
}
/* 统计卡片 */
.stats-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 2rem;
}
.stat-card {
background: white;
border-radius: 12px;
padding: 1.5rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
display: flex;
align-items: center;
gap: 1rem;
}
.stat-card:hover {
transform: translateY(-4px);
}
.stat-icon {
width: 60px;
height: 60px;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
color: white;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.stat-content h3 {
font-size: 2rem;
font-weight: 700;
color: #333;
margin-bottom: 0.25rem;
}
.stat-content p {
color: #666;
font-size: 0.9rem;
}
/* 面板样式 */
.control-panel,
.search-panel,
.data-panel {
background: white;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
margin-bottom: 2rem;
overflow: hidden;
}
.panel-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 1rem 1.5rem;
display: flex;
justify-content: space-between;
align-items: center;
}
.panel-header h2 {
font-size: 1.2rem;
font-weight: 600;
display: flex;
align-items: center;
gap: 10px;
}
.panel-content {
padding: 1.5rem;
}
/* 控制按钮组 */
.control-group h3 {
margin-bottom: 1rem;
color: #333;
font-size: 1.1rem;
}
.control-buttons {
display: flex;
gap: 10px;
flex-wrap: wrap;
}
/* 搜索表单 */
.search-form {
display: flex;
flex-direction: column;
gap: 1rem;
}
.form-row {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}
.form-group {
display: flex;
flex-direction: column;
}
.form-group label {
margin-bottom: 0.5rem;
font-weight: 500;
color: #333;
}
.form-group input,
.form-group select {
padding: 10px 12px;
border: 2px solid #e1e5e9;
border-radius: 8px;
font-size: 14px;
transition: border-color 0.3s ease;
}
.form-group input:focus,
.form-group select:focus {
outline: none;
border-color: #667eea;
}
.form-actions {
display: flex;
gap: 10px;
justify-content: flex-start;
}
/* 数据表格 */
.data-count {
color: white;
font-size: 0.9rem;
}
.panel-actions {
display: flex;
align-items: center;
gap: 10px;
}
.btn-sm {
padding: 6px 12px;
font-size: 12px;
}
.table-container {
overflow-x: auto;
}
.data-table {
width: 100%;
border-collapse: collapse;
font-size: 14px;
}
.data-table th,
.data-table td {
padding: 12px;
text-align: left;
border-bottom: 1px solid #e1e5e9;
}
.data-table th {
background: #f8f9fa;
font-weight: 600;
color: #333;
position: sticky;
top: 0;
}
.data-table tbody tr:hover {
background: #f8f9fa;
}
.no-data {
text-align: center;
color: #666;
font-style: italic;
}
/* 加载和消息提示 */
.loading,
.message {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
}
.loading {
background: rgba(0, 0, 0, 0.5);
}
.loading-content {
background: white;
padding: 2rem;
border-radius: 12px;
text-align: center;
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #667eea;
border-radius: 50%;
animation: spin 1s linear infinite;
margin: 0 auto 1rem;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
.message {
background: rgba(0, 0, 0, 0.3);
pointer-events: none;
}
.message-content {
background: white;
padding: 1rem 1.5rem;
border-radius: 8px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
display: flex;
align-items: center;
gap: 1rem;
pointer-events: all;
}
.message-close {
background: none;
border: none;
font-size: 1.2rem;
cursor: pointer;
color: #666;
}
.hidden {
display: none !important;
}
/* 模态框样式 */
.modal {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, 0.5);
z-index: 2000;
display: flex;
align-items: center;
justify-content: center;
padding: 2rem;
}
.modal-content {
background: white;
border-radius: 12px;
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.3);
max-width: 900px;
width: 100%;
max-height: 90vh;
overflow: hidden;
display: flex;
flex-direction: column;
}
.modal-header {
padding: 1.5rem;
border-bottom: 1px solid #e1e5e9;
display: flex;
justify-content: space-between;
align-items: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
.modal-header h2 {
margin: 0;
font-size: 1.3rem;
font-weight: 600;
}
.modal-close {
background: none;
border: none;
color: white;
font-size: 1.5rem;
cursor: pointer;
padding: 5px;
border-radius: 4px;
transition: background-color 0.3s ease;
}
.modal-close:hover {
background-color: rgba(255, 255, 255, 0.1);
}
.modal-body {
flex: 1;
overflow-y: auto;
padding: 1.5rem;
}
.modal-footer {
padding: 1rem 1.5rem;
border-top: 1px solid #e1e5e9;
display: flex;
gap: 10px;
justify-content: flex-end;
background: #f8f9fa;
}
/* 报告详情样式 */
.report-meta {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
margin-bottom: 2rem;
padding: 1rem;
background: #f8f9fa;
border-radius: 8px;
}
.meta-item {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.meta-item label {
font-weight: 600;
color: #666;
font-size: 0.9rem;
}
.meta-item span {
color: #333;
font-size: 1rem;
}
.report-content .content-section {
margin-bottom: 2rem;
}
.report-content .content-section h3 {
color: #333;
font-size: 1.1rem;
font-weight: 600;
margin-bottom: 0.75rem;
padding-bottom: 0.5rem;
border-bottom: 2px solid #667eea;
}
.content-text {
background: #f8f9fa;
padding: 1rem;
border-radius: 8px;
line-height: 1.6;
color: #333;
}
.content-html {
background: white;
padding: 1rem;
border: 1px solid #e1e5e9;
border-radius: 8px;
line-height: 1.6;
color: #333;
}
.content-html p {
margin-bottom: 1rem;
}
/* 设置页面样式 */
.settings-panel {
background: white;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.settings-group {
margin-bottom: 2rem;
}
.settings-group h3 {
color: #333;
font-size: 1.1rem;
font-weight: 600;
margin-bottom: 1rem;
padding-bottom: 0.5rem;
border-bottom: 2px solid #667eea;
}
.setting-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.75rem 0;
border-bottom: 1px solid #f0f0f0;
}
.setting-item:last-child {
border-bottom: none;
}
.setting-item label {
font-weight: 500;
color: #333;
}
.setting-item input {
padding: 8px 12px;
border: 1px solid #e1e5e9;
border-radius: 6px;
font-size: 14px;
width: 120px;
}
.setting-item input[type="checkbox"] {
width: auto;
transform: scale(1.2);
}
.settings-actions {
display: flex;
gap: 10px;
justify-content: flex-end;
margin-top: 2rem;
}
/* 仪表板样式 */
.metrics-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
gap: 20px;
margin-bottom: 2rem;
}
.metric-card {
background: white;
border-radius: 12px;
padding: 1.5rem;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
transition: transform 0.3s ease;
display: flex;
align-items: center;
gap: 1rem;
border-left: 4px solid #667eea;
}
.metric-card:hover {
transform: translateY(-4px);
}
.metric-icon {
width: 60px;
height: 60px;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.5rem;
color: white;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.metric-content h3 {
font-size: 2rem;
font-weight: 700;
color: #333;
margin: 0 0 0.25rem 0;
}
.metric-content p {
color: #666;
font-size: 0.9rem;
margin: 0 0 0.5rem 0;
}
.metric-change {
font-size: 0.8rem;
font-weight: 600;
padding: 2px 8px;
border-radius: 12px;
}
.metric-change.positive {
background: #d4edda;
color: #155724;
}
.metric-change.negative {
background: #f8d7da;
color: #721c24;
}
.metric-label {
font-size: 0.8rem;
color: #666;
font-weight: 500;
}
/* 图表区域 */
.charts-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
gap: 20px;
}
.chart-panel {
background: white;
border-radius: 12px;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
overflow: hidden;
}
.chart-panel .panel-header {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
padding: 1rem 1.5rem;
display: flex;
justify-content: space-between;
align-items: center;
}
.chart-panel .panel-header h2 {
font-size: 1.1rem;
font-weight: 600;
margin: 0;
display: flex;
align-items: center;
gap: 10px;
}
.chart-controls {
display: flex;
gap: 10px;
align-items: center;
}
.time-range-select {
padding: 6px 12px;
border: 1px solid rgba(255, 255, 255, 0.3);
border-radius: 6px;
background: rgba(255, 255, 255, 0.1);
color: white;
font-size: 0.9rem;
cursor: pointer;
transition: all 0.3s ease;
}
.time-range-select:hover {
background: rgba(255, 255, 255, 0.2);
}
.time-range-select option {
background: #333;
color: white;
}
.chart-panel .panel-content {
padding: 1.5rem;
}
.chart-panel canvas {
max-width: 100%;
height: auto;
}
/* 活跃度网格 */
.activity-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 1rem;
}
.activity-item {
text-align: center;
padding: 1rem;
background: #f8f9fa;
border-radius: 8px;
border: 2px solid transparent;
transition: all 0.3s ease;
}
.activity-item:hover {
border-color: #667eea;
background: #f0f4ff;
}
.activity-item h4 {
font-size: 0.9rem;
color: #666;
margin: 0 0 0.5rem 0;
font-weight: 500;
}
.activity-value {
font-size: 1.5rem;
font-weight: 700;
color: #333;
margin: 0;
}
/* 图表响应式 */
@media (max-width: 768px) {
.metrics-grid {
grid-template-columns: 1fr;
}
.charts-grid {
grid-template-columns: 1fr;
}
.chart-panel .panel-header {
flex-direction: column;
gap: 1rem;
align-items: flex-start;
}
.activity-grid {
grid-template-columns: repeat(2, 1fr);
}
}
@media (max-width: 480px) {
.metric-card {
flex-direction: column;
text-align: center;
}
.activity-grid {
grid-template-columns: 1fr;
}
}
/* 分页样式 */
.pagination-container {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 0;
border-top: 1px solid #e1e5e9;
margin-top: 1rem;
}
.pagination-info {
display: flex;
flex-direction: column;
gap: 0.25rem;
color: #666;
font-size: 0.9rem;
}
.pagination-controls {
display: flex;
align-items: center;
gap: 0.5rem;
}
.page-numbers {
display: flex;
gap: 0.25rem;
margin: 0 0.5rem;
}
.page-number {
padding: 6px 12px;
border: 1px solid #e1e5e9;
background: white;
color: #333;
text-decoration: none;
border-radius: 4px;
font-size: 0.9rem;
cursor: pointer;
transition: all 0.3s ease;
}
.page-number:hover {
background: #f8f9fa;
border-color: #667eea;
}
.page-number.active {
background: #667eea;
color: white;
border-color: #667eea;
}
.page-number.disabled {
background: #f8f9fa;
color: #ccc;
cursor: not-allowed;
border-color: #f0f0f0;
}
@media (max-width: 768px) {
.pagination-container {
flex-direction: column;
gap: 1rem;
align-items: stretch;
}
.pagination-controls {
justify-content: center;
flex-wrap: wrap;
}
.pagination-info {
text-align: center;
}
}
/* 响应式设计 */
@media (max-width: 768px) {
.sidebar {
transform: translateX(-100%);
}
.sidebar.show {
transform: translateX(0);
}
.main-content {
margin-left: 0;
}
.mobile-toggle {
display: block;
}
.sidebar-toggle {
display: block;
}
.header-content {
padding: 1rem;
}
.header-title h1 {
font-size: 1.2rem;
}
.stats-grid {
grid-template-columns: 1fr;
}
.form-row {
grid-template-columns: 1fr;
}
.control-buttons {
flex-direction: column;
}
.form-actions {
flex-direction: column;
}
.action-grid {
grid-template-columns: 1fr;
}
.modal {
padding: 1rem;
}
.modal-content {
max-height: 95vh;
}
.report-meta {
grid-template-columns: 1fr;
}
.modal-footer {
flex-direction: column;
}
.setting-item {
flex-direction: column;
align-items: flex-start;
gap: 0.5rem;
}
}
@media (max-width: 480px) {
.content-wrapper {
padding: 1rem;
}
.panel-content {
padding: 1rem;
}
.table-container {
font-size: 0.85rem;
}
.btn {
padding: 8px 16px;
font-size: 0.9rem;
}
.btn-sm {
padding: 4px 8px;
font-size: 0.8rem;
}
}
/* 报告类型过滤器样式 */
.report-type-filter {
padding: 1rem 1.5rem;
background: #f8f9fa;
border-bottom: 1px solid #e1e5e9;
}
.filter-group {
display: flex;
align-items: center;
gap: 1rem;
flex-wrap: wrap;
}
.filter-group label {
font-weight: 600;
color: #333;
font-size: 0.95rem;
white-space: nowrap;
}
.btn-group {
display: flex;
gap: 0.5rem;
flex-wrap: wrap;
}
.btn-outline-primary {
background: white;
color: #007bff;
border: 2px solid #007bff;
transition: all 0.3s ease;
}
.btn-outline-primary:hover {
background: #007bff;
color: white;
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
}
.btn-outline-primary.active {
background: #007bff;
color: white;
box-shadow: 0 4px 12px rgba(0, 123, 255, 0.3);
}
.report-type-btn {
position: relative;
font-size: 0.9rem;
font-weight: 500;
white-space: nowrap;
}
.report-type-btn i {
margin-right: 0.5rem;
}
/* 响应式报告类型过滤器 */
@media (max-width: 768px) {
.filter-group {
flex-direction: column;
align-items: flex-start;
gap: 0.75rem;
}
.btn-group {
width: 100%;
justify-content: space-between;
}
.report-type-btn {
flex: 1;
text-align: center;
font-size: 0.85rem;
padding: 8px 12px;
}
}
@media (max-width: 480px) {
.btn-group {
flex-direction: column;
gap: 0.5rem;
}
.report-type-btn {
width: 100%;
justify-content: center;
}
}
/* 仪表盘样式 */
.dashboard-container {
padding: 1.5rem;
max-width: 1200px;
margin: 0 auto;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
min-height: 100vh;
position: relative;
}
.dashboard-container::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background:
radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
radial-gradient(circle at 80% 20%, rgba(255, 255, 255, 0.15) 0%, transparent 50%),
radial-gradient(circle at 40% 40%, rgba(120, 119, 198, 0.2) 0%, transparent 50%);
pointer-events: none;
}
.overview-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
gap: 1.5rem;
margin-bottom: 2.5rem;
animation: fadeInUp 0.8s ease-out;
}
@keyframes fadeInUp {
0% {
opacity: 0;
transform: translateY(30px);
}
100% {
opacity: 1;
transform: translateY(0);
}
}
.overview-card {
display: flex;
align-items: center;
padding: 1.5rem;
background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
border: none;
border-radius: 16px;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
transition: all 0.4s cubic-bezier(0.175, 0.885, 0.32, 1.275);
position: relative;
overflow: hidden;
opacity: 0;
animation: cardSlideIn 0.6s ease-out forwards;
}
.overview-card:nth-child(1) { animation-delay: 0.1s; }
.overview-card:nth-child(2) { animation-delay: 0.2s; }
.overview-card:nth-child(3) { animation-delay: 0.3s; }
.overview-card:nth-child(4) { animation-delay: 0.4s; }
@keyframes cardSlideIn {
0% {
opacity: 0;
transform: translateX(-50px) scale(0.8);
}
100% {
opacity: 1;
transform: translateX(0) scale(1);
}
}
.overview-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
transform: scaleX(0);
transition: transform 0.3s ease;
}
.overview-card:hover::before {
transform: scaleX(1);
}
.overview-card:hover {
transform: translateY(-4px) scale(1.01);
box-shadow: 0 12px 25px rgba(0, 0, 0, 0.15);
}
.overview-card .card-icon {
width: 50px;
height: 50px;
border-radius: 12px;
display: flex;
align-items: center;
justify-content: center;
margin-right: 1rem;
font-size: 1.4rem;
color: white;
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
position: relative;
}
.overview-card .card-icon::after {
content: '';
position: absolute;
inset: 2px;
border-radius: 10px;
background: linear-gradient(135deg, rgba(255,255,255,0.2) 0%, rgba(255,255,255,0.05) 100%);
pointer-events: none;
}
.overview-card:nth-child(1) .card-icon {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
}
.overview-card:nth-child(2) .card-icon {
background: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
box-shadow: 0 8px 20px rgba(17, 153, 142, 0.4);
}
.overview-card:nth-child(3) .card-icon {
background: linear-gradient(135deg, #ffecd2 0%, #fcb69f 100%);
box-shadow: 0 8px 20px rgba(252, 182, 159, 0.4);
}
.overview-card:nth-child(4) .card-icon {
background: linear-gradient(135deg, #ff9a9e 0%, #fecfef 100%);
box-shadow: 0 8px 20px rgba(255, 154, 158, 0.4);
}
.overview-card .card-content h3 {
margin: 0 0 0.5rem 0;
font-size: 0.85rem;
color: #6c757d;
font-weight: 600;
text-transform: uppercase;
letter-spacing: 0.5px;
}
.metric-value {
font-size: 1.6rem;
font-weight: 700;
background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
margin-bottom: 0.4rem;
line-height: 1.2;
}
.metric-change {
font-size: 0.75rem;
font-weight: 600;
padding: 0.3rem 0.6rem;
border-radius: 8px;
display: inline-block;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}
.metric-change.positive {
background: linear-gradient(135deg, #d4edda 0%, #c3e6cb 100%);
color: #155724;
border: 1px solid #c3e6cb;
}
.metric-change.negative {
background: linear-gradient(135deg, #f8d7da 0%, #f5c6cb 100%);
color: #721c24;
border: 1px solid #f5c6cb;
}
.charts-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(480px, 1fr));
gap: 1.8rem;
margin-bottom: 2.5rem;
animation: fadeInUp 1s ease-out 0.5s both;
}
.chart-card {
background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
border: none;
border-radius: 16px;
overflow: hidden;
box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
position: relative;
}
.chart-card::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
height: 4px;
background: linear-gradient(90deg, #667eea 0%, #764ba2 100%);
}
.chart-card:hover {
transform: translateY(-3px);
box-shadow: 0 12px 25px rgba(0, 0, 0, 0.15);
}
.chart-card .card-header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1.5rem 1.5rem 0.8rem 1.5rem;
background: transparent;
border-bottom: none;
}
.chart-card .card-header h3 {
margin: 0;
font-size: 1.1rem;
background: linear-gradient(135deg, #2c3e50 0%, #34495e 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
font-weight: 600;
}
.chart-controls {
display: flex;
align-items: center;
gap: 0.75rem;
}
.chart-controls select {
padding: 0.5rem 1rem;
border: 2px solid #e9ecef;
border-radius: 12px;
font-size: 0.9rem;
background: linear-gradient(135deg, #ffffff 0%, #f8f9fa 100%);
font-weight: 600;
color: #495057;
transition: all 0.3s ease;
}
.chart-controls select:focus {
outline: none;
border-color: #667eea;
box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.1);
}
.chart-card .card-body {
padding: 0 1.5rem 1.5rem 1.5rem;
height: 320px;
position: relative;
}
.volatility-container {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 2rem;
height: 100%;
}
.volatility-section h4 {
margin: 0 0 1.5rem 0;
font-size: 1.1rem;
font-weight: 700;
display: flex;
align-items: center;
gap: 0.75rem;
color: #2c3e50;
padding-bottom: 0.5rem;
border-bottom: 2px solid #e9ecef;
}
.volatility-list {
display: flex;
flex-direction: column;
gap: 1rem;
}
/* 美化按钮样式 */
.btn-refresh {
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
border: none;
padding: 0.6rem 1.2rem;
border-radius: 10px;
font-weight: 600;
font-size: 0.85rem;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 3px 10px rgba(102, 126, 234, 0.3);
position: relative;
overflow: hidden;
}
.btn-refresh::before {
content: '';
position: absolute;
top: 0;
left: -100%;
width: 100%;
height: 100%;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
transition: left 0.5s;
}
.btn-refresh:hover::before {
left: 100%;
}
.btn-refresh:hover {
transform: translateY(-1px);
box-shadow: 0 5px 15px rgba(102, 126, 234, 0.4);
}
.btn-refresh:active {
transform: translateY(0);
}
/* 美化标题 */
.dashboard-container h1 {
text-align: center;
color: white;
font-size: 2.2rem;
font-weight: 700;
margin-bottom: 2rem;
text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
position: relative;
animation: titleGlow 3s ease-in-out infinite alternate;
}
.dashboard-container h1::after {
content: '';
position: absolute;
bottom: -10px;
left: 50%;
transform: translateX(-50%);
width: 80px;
height: 3px;
background: linear-gradient(90deg, transparent, rgba(255,255,255,0.8), transparent);
border-radius: 2px;
animation: underlineGlow 2s ease-in-out infinite alternate;
}
@keyframes titleGlow {
0% { text-shadow: 0 4px 20px rgba(0, 0, 0, 0.3); }
100% { text-shadow: 0 4px 30px rgba(255, 255, 255, 0.2), 0 0 40px rgba(255, 255, 255, 0.1); }
}
@keyframes underlineGlow {
0% { box-shadow: 0 0 5px rgba(255, 255, 255, 0.3); }
100% { box-shadow: 0 0 20px rgba(255, 255, 255, 0.6); }
}
/* 加载动画美化 */
.loading-overlay {
background: linear-gradient(135deg, rgba(102, 126, 234, 0.95) 0%, rgba(118, 75, 162, 0.95) 100%);
backdrop-filter: blur(10px);
}
.loading-spinner {
background: rgba(255, 255, 255, 0.1);
border-radius: 20px;
padding: 3rem;
box-shadow: 0 20px 40px rgba(0, 0, 0, 0.2);
}
.loading-spinner i {
font-size: 3rem;
color: white;
margin-bottom: 1rem;
animation: spin 1s linear infinite, pulse 2s ease-in-out infinite alternate;
}
.loading-spinner p {
color: white;
font-size: 1.2rem;
font-weight: 600;
text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}
@keyframes pulse {
0% { transform: scale(1); }
100% { transform: scale(1.1); }
}
/* 响应式设计改进 */
@media (max-width: 768px) {
.dashboard-container {
padding: 1rem;
}
.dashboard-container h1 {
font-size: 1.8rem;
margin-bottom: 1.5rem;
}
.overview-cards {
grid-template-columns: 1fr;
gap: 1rem;
margin-bottom: 1.5rem;
}
.overview-card {
padding: 1.2rem;
}
.overview-card .card-icon {
width: 45px;
height: 45px;
font-size: 1.2rem;
margin-right: 0.8rem;
}
.metric-value {
font-size: 1.4rem;
}
.charts-container {
grid-template-columns: 1fr;
gap: 1.5rem;
}
.chart-card .card-header {
padding: 1.2rem 1.2rem 0.8rem 1.2rem;
}
.chart-card .card-body {
padding: 0 1.2rem 1.2rem 1.2rem;
height: 280px;
}
}
@media (max-width: 480px) {
.dashboard-container h1 {
font-size: 1.6rem;
}
.overview-card {
flex-direction: column;
text-align: center;
padding: 1rem;
}
.overview-card .card-icon {
margin-right: 0;
margin-bottom: 0.8rem;
width: 40px;
height: 40px;
font-size: 1.1rem;
}
.metric-value {
font-size: 1.3rem;
}
}
.volatility-item {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.75rem;
background: #f8f9fa;
border-radius: 8px;
border-left: 4px solid transparent;
}
.volatility-item:has(.positive) {
border-left-color: #28a745;
}
.volatility-item:has(.negative) {
border-left-color: #dc3545;
}
.product-name {
font-weight: 500;
color: #333;
}
.change-rate {
font-weight: 600;
font-size: 0.9rem;
}
.change-rate.positive {
color: #28a745;
}
.change-rate.negative {
color: #dc3545;
}
.summary-section {
margin-top: 2rem;
}
.summary-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
}
.summary-item {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.summary-item label {
font-size: 0.875rem;
color: #6c757d;
font-weight: 500;
}
.summary-item span {
font-size: 1rem;
color: #333;
font-weight: 600;
}
/* 响应式设计 */
@media (max-width: 1200px) {
.charts-container {
grid-template-columns: 1fr;
}
.chart-card .card-body {
height: 350px;
}
}
@media (max-width: 768px) {
.dashboard-container {
padding: 1rem;
}
.overview-cards {
grid-template-columns: 1fr;
gap: 1rem;
}
.overview-card {
padding: 1rem;
}
.overview-card .card-icon {
width: 50px;
height: 50px;
font-size: 1.25rem;
}
.metric-value {
font-size: 1.5rem;
}
.chart-card .card-header {
flex-direction: column;
align-items: flex-start;
gap: 1rem;
}
.chart-controls {
width: 100%;
justify-content: flex-end;
}
.chart-card .card-body {
height: 300px;
padding: 1rem;
}
.volatility-container {
grid-template-columns: 1fr;
gap: 1.5rem;
}
.summary-grid {
grid-template-columns: 1fr;
}
}
/* 仪表盘预览样式 */
.dashboard-embed-container {
padding: 1.5rem;
}
.dashboard-actions {
display: flex;
gap: 1rem;
margin-bottom: 2rem;
justify-content: center;
}
.dashboard-preview {
margin-bottom: 2rem;
}
.preview-cards {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
gap: 1rem;
margin-bottom: 2rem;
}
.preview-card {
display: flex;
align-items: center;
padding: 1rem;
background: white;
border: 1px solid #e1e5e9;
border-radius: 8px;
box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
transition: all 0.3s ease;
}
.preview-card:hover {
transform: translateY(-2px);
box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}
.preview-card .card-icon {
width: 40px;
height: 40px;
border-radius: 8px;
display: flex;
align-items: center;
justify-content: center;
margin-right: 0.75rem;
font-size: 1.2rem;
color: white;
}
.preview-card .card-icon.price-index {
background: linear-gradient(135deg, #007bff, #0056b3);
}
.preview-card .card-icon.vegetables {
background: linear-gradient(135deg, #28a745, #1e7e34);
}
.preview-card .card-icon.fruits {
background: linear-gradient(135deg, #ffc107, #e0a800);
}
.preview-card .card-icon.meat {
background: linear-gradient(135deg, #dc3545, #c82333);
}
.preview-card .card-content h3 {
margin: 0 0 0.25rem 0;
font-size: 0.8rem;
color: #6c757d;
font-weight: 500;
}
.preview-card .metric-value {
font-size: 1.2rem;
font-weight: 700;
color: #333;
margin-bottom: 0.125rem;
}
.preview-card .metric-change {
font-size: 0.75rem;
font-weight: 600;
}
.chart-preview {
background: white;
border: 1px solid #e1e5e9;
border-radius: 8px;
padding: 1rem;
margin-bottom: 1.5rem;
}
.chart-preview h4 {
margin: 0 0 1rem 0;
font-size: 0.95rem;
color: #333;
font-weight: 600;
display: flex;
align-items: center;
gap: 0.5rem;
}
.chart-container {
height: 200px;
position: relative;
}
.dashboard-summary {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
gap: 1rem;
padding: 1rem;
background: #f8f9fa;
border-radius: 8px;
}
.dashboard-summary .summary-item {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.dashboard-summary .summary-item label {
font-size: 0.8rem;
color: #6c757d;
font-weight: 500;
}
.dashboard-summary .summary-item span {
font-size: 0.9rem;
color: #333;
font-weight: 600;
}
/* 响应式设计 */
@media (max-width: 768px) {
.dashboard-actions {
flex-direction: column;
align-items: center;
}
.preview-cards {
grid-template-columns: 1fr;
}
.preview-card {
padding: 0.75rem;
}
.preview-card .card-icon {
width: 35px;
height: 35px;
font-size: 1rem;
}
.chart-container {
height: 150px;
}
.dashboard-summary {
grid-template-columns: 1fr;
}
}
/* 爬取选项样式 */
.crawl-options {
margin-top: 1.5rem;
padding: 1rem;
background: #f8f9fa;
border-radius: 8px;
border: 1px solid #e1e5e9;
}
.crawl-options h4 {
margin: 0 0 1rem 0;
color: #333;
font-size: 1rem;
font-weight: 600;
}
.crawl-options .form-group {
margin-bottom: 1rem;
}
.crawl-options .form-group label {
display: flex;
align-items: flex-start;
gap: 0.5rem;
font-weight: 500;
color: #333;
cursor: pointer;
}
.crawl-options .form-group input[type="checkbox"] {
margin-top: 0.2rem;
transform: scale(1.2);
}
.help-text {
display: block;
margin-top: 0.5rem;
font-size: 0.85rem;
color: #666;
line-height: 1.4;
}
.crawl-options .control-buttons {
margin-top: 1rem;
}
@media (max-width: 768px) {
.crawl-options {
margin-top: 1rem;
padding: 0.75rem;
}
.crawl-options h4 {
font-size: 0.95rem;
}
.help-text {
font-size: 0.8rem;
}
}
|
2301_78526554/agricultural-platform
|
static/css/style.css
|
CSS
|
unknown
| 37,254
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数据仪表盘 - 农产品市场价格管理平台</title>
<link rel="stylesheet" href="/static/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<script src="https://cdn.jsdelivr.net/npm/date-fns@2.29.3/index.min.js"></script>
</head>
<body>
<div class="container">
<!-- 导航栏 -->
<nav class="navbar">
<div class="nav-brand">
<i class="fas fa-chart-line"></i>
<span>数据仪表盘</span>
</div>
<div class="nav-links">
<a href="/"><i class="fas fa-home"></i> 首页</a>
<a href="/static/dashboard.html" class="active"><i class="fas fa-chart-bar"></i> 仪表盘</a>
<a href="/#reports"><i class="fas fa-file-alt"></i> 报告</a>
<a href="/#management"><i class="fas fa-cog"></i> 管理</a>
</div>
</nav>
<!-- 加载状态 -->
<div id="loadingIndicator" class="loading-overlay">
<div class="loading-spinner">
<i class="fas fa-spinner fa-spin"></i>
<p>正在加载数据...</p>
</div>
</div>
<!-- 仪表盘内容 -->
<div class="dashboard-container">
<!-- 标题 -->
<h1>🌾 农产品市场数据仪表盘</h1>
<!-- 刷新按钮 -->
<div style="text-align: center; margin-bottom: 2rem;">
<button class="btn-refresh" onclick="refreshDashboard()">
🔄 刷新数据
</button>
</div>
<!-- 概览卡片 -->
<div class="overview-cards">
<div class="card overview-card">
<div class="card-icon">
<i class="fas fa-chart-line"></i>
</div>
<div class="card-content">
<h3>价格指数</h3>
<div class="metric-value" id="latestPriceIndex">--</div>
<div class="metric-change" id="priceIndexChange">--</div>
</div>
</div>
<div class="card overview-card">
<div class="card-icon">
<i class="fas fa-carrot"></i>
</div>
<div class="card-content">
<h3>蔬菜均价</h3>
<div class="metric-value" id="latestVegPrice">--</div>
<div class="metric-change" id="vegPriceChange">--</div>
</div>
</div>
<div class="card overview-card">
<div class="card-icon">
<i class="fas fa-apple-alt"></i>
</div>
<div class="card-content">
<h3>水果均价</h3>
<div class="metric-value" id="latestFruitPrice">--</div>
<div class="metric-change" id="fruitPriceChange">--</div>
</div>
</div>
<div class="card overview-card">
<div class="card-icon">
<i class="fas fa-drumstick-bite"></i>
</div>
<div class="card-content">
<h3>猪肉价格</h3>
<div class="metric-value" id="latestMeatPrice">--</div>
<div class="metric-change" id="meatPriceChange">--</div>
</div>
</div>
</div>
<!-- 图表区域 -->
<div class="charts-container">
<!-- 价格指数趋势图 -->
<div class="card chart-card">
<div class="card-header">
<h3><i class="fas fa-chart-line"></i> 农产品批发价格指数趋势</h3>
<div class="chart-controls">
<button class="btn btn-sm btn-outline-primary" onclick="refreshChart('priceIndex')">
<i class="fas fa-sync-alt"></i> 刷新
</button>
</div>
</div>
<div class="card-body">
<canvas id="priceIndexChart"></canvas>
</div>
</div>
<!-- 各类别价格趋势图 -->
<div class="card chart-card">
<div class="card-header">
<h3><i class="fas fa-chart-area"></i> 各类别价格趋势</h3>
<div class="chart-controls">
<select id="categorySelect" onchange="updateCategoryChart()">
<option value="all">全部类别</option>
<option value="vegetables">蔬菜</option>
<option value="fruits">水果</option>
<option value="meat">畜产品</option>
<option value="aquatic">水产品</option>
</select>
<button class="btn btn-sm btn-outline-primary" onclick="refreshChart('category')">
<i class="fas fa-sync-alt"></i> 刷新
</button>
</div>
</div>
<div class="card-body">
<canvas id="categoryChart"></canvas>
</div>
</div>
<!-- 重点产品价格对比 -->
<div class="card chart-card">
<div class="card-header">
<h3><i class="fas fa-chart-bar"></i> 重点产品价格对比</h3>
<div class="chart-controls">
<button class="btn btn-sm btn-outline-primary" onclick="refreshChart('products')">
<i class="fas fa-sync-alt"></i> 刷新
</button>
</div>
</div>
<div class="card-body">
<canvas id="productsChart"></canvas>
</div>
</div>
<!-- 价格波动分析 -->
<div class="card chart-card">
<div class="card-header">
<h3><i class="fas fa-chart-pie"></i> 价格波动分析</h3>
<div class="chart-controls">
<button class="btn btn-sm btn-outline-primary" onclick="refreshChart('volatility')">
<i class="fas fa-sync-alt"></i> 刷新
</button>
</div>
</div>
<div class="card-body">
<div class="volatility-container">
<div class="volatility-section">
<h4><i class="fas fa-arrow-up text-success"></i> 涨幅前五</h4>
<div id="topGainers" class="volatility-list"></div>
</div>
<div class="volatility-section">
<h4><i class="fas fa-arrow-down text-danger"></i> 跌幅前五</h4>
<div id="topLosers" class="volatility-list"></div>
</div>
</div>
</div>
</div>
</div>
<!-- 数据摘要 -->
<div class="summary-section">
<div class="card">
<div class="card-header">
<h3><i class="fas fa-info-circle"></i> 数据摘要</h3>
</div>
<div class="card-body">
<div class="summary-grid">
<div class="summary-item">
<label>数据时间范围:</label>
<span id="dateRange">--</span>
</div>
<div class="summary-item">
<label>报告总数:</label>
<span id="totalReports">--</span>
</div>
<div class="summary-item">
<label>最后更新:</label>
<span id="lastUpdate">--</span>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- 消息提示 -->
<div id="messageContainer" class="message-container"></div>
<script src="/static/js/dashboard.js"></script>
</body>
</html>
|
2301_78526554/agricultural-platform
|
static/dashboard.html
|
HTML
|
unknown
| 9,263
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>农产品市场价格管理平台</title>
<link rel="stylesheet" href="/static/css/style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/chart.min.js"></script>
</head>
<body>
<div id="app">
<!-- 侧边栏 -->
<aside class="sidebar" id="sidebar">
<div class="sidebar-header">
<div class="logo">
<i class="fas fa-seedling"></i>
<h2>农产品平台</h2>
</div>
<button class="sidebar-toggle" onclick="toggleSidebar()">
<i class="fas fa-times"></i>
</button>
</div>
<nav class="sidebar-nav">
<ul class="nav-list">
<li class="nav-item">
<a href="#dashboard" class="nav-link active" onclick="showSection('dashboard')">
<i class="fas fa-tachometer-alt"></i>
<span>数据概览</span>
</a>
</li>
<li class="nav-item">
<a href="#trends" class="nav-link" onclick="showSection('trends')">
<i class="fas fa-chart-area"></i>
<span>趋势仪表板</span>
</a>
</li>
<li class="nav-item">
<a href="#price-data" class="nav-link" onclick="showSection('price-data')">
<i class="fas fa-chart-line"></i>
<span>价格数据</span>
</a>
</li>
<li class="nav-item">
<a href="#reports" class="nav-link" onclick="showSection('reports')">
<i class="fas fa-file-alt"></i>
<span>分析报告</span>
</a>
</li>
<li class="nav-item">
<a href="#crawler-control" class="nav-link" onclick="showSection('crawler-control')">
<i class="fas fa-cogs"></i>
<span>爬虫控制</span>
</a>
</li>
<li class="nav-item">
<a href="#settings" class="nav-link" onclick="showSection('settings')">
<i class="fas fa-cog"></i>
<span>系统设置</span>
</a>
</li>
</ul>
</nav>
</aside>
<!-- 主要内容区域 -->
<main class="main-content">
<!-- 顶部导航栏 -->
<header class="header">
<div class="header-content">
<button class="sidebar-toggle mobile-toggle" onclick="toggleSidebar()">
<i class="fas fa-bars"></i>
</button>
<div class="header-title">
<h1 id="pageTitle">数据概览</h1>
</div>
<div class="header-actions">
<button class="btn btn-primary" onclick="refreshCurrentSection()">
<i class="fas fa-sync-alt"></i> 刷新
</button>
<button class="btn btn-success" onclick="exportCurrentData()">
<i class="fas fa-download"></i> 导出
</button>
</div>
</div>
</header>
<!-- 内容区域 -->
<div class="content-wrapper">
<!-- 数据概览页面 -->
<section id="dashboard-section" class="content-section active">
<!-- 统计卡片 -->
<div class="stats-grid">
<div class="stat-card">
<div class="stat-icon">
<i class="fas fa-database"></i>
</div>
<div class="stat-content">
<h3 id="totalRecords">-</h3>
<p>总记录数</p>
</div>
</div>
<div class="stat-card">
<div class="stat-icon">
<i class="fas fa-store"></i>
</div>
<div class="stat-content">
<h3 id="totalMarkets">-</h3>
<p>市场数量</p>
</div>
</div>
<div class="stat-card">
<div class="stat-icon">
<i class="fas fa-leaf"></i>
</div>
<div class="stat-content">
<h3 id="totalVarieties">-</h3>
<p>品种数量</p>
</div>
</div>
<div class="stat-card">
<div class="stat-icon">
<i class="fas fa-robot"></i>
</div>
<div class="stat-content">
<h3 id="crawlerStatus">-</h3>
<p>爬虫状态</p>
</div>
</div>
</div>
<!-- 快速操作 -->
<div class="quick-actions">
<div class="panel-header">
<h2><i class="fas fa-bolt"></i> 快速操作</h2>
</div>
<div class="action-grid">
<button class="action-card" onclick="showSection('price-data')">
<i class="fas fa-chart-line"></i>
<h3>查看价格数据</h3>
<p>浏览最新的农产品价格信息</p>
</button>
<button class="action-card" onclick="showSection('reports')">
<i class="fas fa-file-alt"></i>
<h3>分析报告</h3>
<p>查看农业部发布的分析报告</p>
</button>
<button class="action-card" onclick="startCrawler()">
<i class="fas fa-play"></i>
<h3>启动爬虫</h3>
<p>开始爬取最新数据</p>
</button>
<button class="action-card" onclick="exportData()">
<i class="fas fa-download"></i>
<h3>导出数据</h3>
<p>下载价格数据到本地</p>
</button>
</div>
</div>
</section>
<!-- 趋势仪表板页面 -->
<section id="trends-section" class="content-section">
<div class="section-header">
<h2><i class="fas fa-chart-area"></i> 趋势仪表板</h2>
<p>基于分析报告的关键数据趋势可视化</p>
</div>
<!-- 仪表盘内容容器 -->
<div class="dashboard-embed-container">
<div class="dashboard-actions">
<button class="btn btn-primary" onclick="openDashboard()">
<i class="fas fa-external-link-alt"></i> 打开完整仪表盘
</button>
<button class="btn btn-outline-primary" onclick="refreshDashboardData()">
<i class="fas fa-sync-alt"></i> 刷新数据
</button>
</div>
<!-- 关键指标预览 -->
<div class="dashboard-preview">
<div class="preview-cards">
<div class="preview-card">
<div class="card-icon price-index">
<i class="fas fa-chart-line"></i>
</div>
<div class="card-content">
<h3>价格指数</h3>
<div class="metric-value" id="dashboardPriceIndex">--</div>
<div class="metric-change" id="dashboardPriceIndexChange">--</div>
</div>
</div>
<div class="preview-card">
<div class="card-icon vegetables">
<i class="fas fa-carrot"></i>
</div>
<div class="card-content">
<h3>蔬菜均价</h3>
<div class="metric-value" id="dashboardVegPrice">--</div>
<div class="metric-change" id="dashboardVegChange">--</div>
</div>
</div>
<div class="preview-card">
<div class="card-icon fruits">
<i class="fas fa-apple-alt"></i>
</div>
<div class="card-content">
<h3>水果均价</h3>
<div class="metric-value" id="dashboardFruitPrice">--</div>
<div class="metric-change" id="dashboardFruitChange">--</div>
</div>
</div>
<div class="preview-card">
<div class="card-icon meat">
<i class="fas fa-drumstick-bite"></i>
</div>
<div class="card-content">
<h3>猪肉价格</h3>
<div class="metric-value" id="dashboardMeatPrice">--</div>
<div class="metric-change" id="dashboardMeatChange">--</div>
</div>
</div>
</div>
<!-- 简化图表预览 -->
<div class="chart-preview">
<div class="chart-container">
<h4><i class="fas fa-chart-line"></i> 价格指数趋势预览</h4>
<canvas id="previewChart"></canvas>
</div>
</div>
</div>
<!-- 数据摘要 -->
<div class="dashboard-summary">
<div class="summary-item">
<label>数据时间范围:</label>
<span id="dashboardDateRange">--</span>
</div>
<div class="summary-item">
<label>报告总数:</label>
<span id="dashboardTotalReports">--</span>
</div>
<div class="summary-item">
<label>最后更新:</label>
<span id="dashboardLastUpdate">--</span>
</div>
</div>
</div>
</section>
<!-- 价格数据页面 -->
<section id="price-data-section" class="content-section">
<!-- 搜索面板 -->
<div class="search-panel">
<div class="panel-header">
<h2><i class="fas fa-search"></i> 数据搜索</h2>
</div>
<div class="panel-content">
<form id="searchForm" class="search-form">
<div class="form-row">
<div class="form-group">
<label for="province">省份</label>
<select id="province" name="province">
<option value="">全部省份</option>
</select>
</div>
<div class="form-group">
<label for="variety">品种</label>
<select id="variety" name="variety">
<option value="">全部品种</option>
</select>
</div>
<div class="form-group">
<label for="market">市场</label>
<select id="market" name="market">
<option value="">全部市场</option>
</select>
</div>
</div>
<div class="form-row">
<div class="form-group">
<label for="dateFrom">开始日期</label>
<input type="date" id="dateFrom" name="date_from">
</div>
<div class="form-group">
<label for="dateTo">结束日期</label>
<input type="date" id="dateTo" name="date_to">
</div>
<div class="form-group">
<label for="limit">记录数量</label>
<select id="limit" name="limit">
<option value="50">50条</option>
<option value="100" selected>100条</option>
<option value="200">200条</option>
<option value="500">500条</option>
</select>
</div>
</div>
<div class="form-actions">
<button type="submit" class="btn btn-primary">
<i class="fas fa-search"></i> 搜索
</button>
<button type="button" class="btn btn-secondary" onclick="resetSearch()">
<i class="fas fa-undo"></i> 重置
</button>
</div>
</form>
</div>
</div>
<!-- 数据表格 -->
<div class="data-panel">
<div class="panel-header">
<h2><i class="fas fa-table"></i> 价格数据列表</h2>
<div class="panel-actions">
<span id="dataCount" class="data-count">共 0 条记录</span>
</div>
</div>
<div class="panel-content">
<div class="table-container">
<table id="dataTable" class="data-table">
<thead>
<tr>
<th>省份</th>
<th>市场名称</th>
<th>品种名称</th>
<th>最低价</th>
<th>平均价</th>
<th>最高价</th>
<th>单位</th>
<th>交易日期</th>
<th>更新时间</th>
</tr>
</thead>
<tbody id="dataTableBody">
<tr>
<td colspan="9" class="no-data">暂无数据</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</section>
<!-- 分析报告页面 -->
<section id="reports-section" class="content-section">
<!-- 分析报告列表 -->
<div class="data-panel">
<div class="panel-header">
<h2><i class="fas fa-file-alt"></i> 分析报告列表</h2>
<div class="panel-actions">
<span id="reportCount" class="data-count">共 0 篇报告</span>
<button class="btn btn-primary btn-sm" onclick="refreshReports()">
<i class="fas fa-sync-alt"></i> 刷新报告
</button>
<button class="btn btn-success btn-sm" onclick="exportReports()">
<i class="fas fa-download"></i> 导出报告
</button>
</div>
</div>
<!-- 报告类型切换 -->
<div class="report-type-filter">
<div class="filter-group">
<label>报告类型:</label>
<div class="btn-group">
<button class="btn btn-sm btn-outline-primary report-type-btn active"
data-report-type="all" onclick="switchReportType('all')">
<i class="fas fa-list"></i> 全部 (<span id="totalReportsCount">0</span>)
</button>
<button class="btn btn-sm btn-outline-primary report-type-btn"
data-report-type="daily" onclick="switchReportType('daily')">
<i class="fas fa-calendar-day"></i> 日报 (<span id="dailyReportsCount">0</span>)
</button>
<button class="btn btn-sm btn-outline-primary report-type-btn"
data-report-type="monthly" onclick="switchReportType('monthly')">
<i class="fas fa-calendar-alt"></i> 月报 (<span id="monthlyReportsCount">0</span>)
</button>
<button class="btn btn-sm btn-outline-primary report-type-btn"
data-report-type="yearly" onclick="switchReportType('yearly')">
<i class="fas fa-calendar"></i> 年报 (<span id="yearlyReportsCount">0</span>)
</button>
</div>
</div>
</div>
<div class="panel-content">
<div class="table-container">
<table id="reportTable" class="data-table">
<thead>
<tr>
<th>报告标题</th>
<th>报告类型</th>
<th>发布时间</th>
<th>来源</th>
<th>爬取时间</th>
<th>操作</th>
</tr>
</thead>
<tbody id="reportTableBody">
<tr>
<td colspan="6" class="no-data">暂无报告数据</td>
</tr>
</tbody>
</table>
</div>
<!-- 分页控件 -->
<div id="reportPagination" class="pagination-container hidden">
<div class="pagination-info">
<span id="reportPageInfo">第 1 页,共 1 页</span>
<span id="reportTotalInfo">总计 0 条记录</span>
</div>
<div class="pagination-controls">
<button class="btn btn-sm btn-secondary" id="reportFirstPage" onclick="goToReportPage(1)">
<i class="fas fa-angle-double-left"></i> 首页
</button>
<button class="btn btn-sm btn-secondary" id="reportPrevPage" onclick="goToReportPage('prev')">
<i class="fas fa-angle-left"></i> 上一页
</button>
<span class="page-numbers" id="reportPageNumbers"></span>
<button class="btn btn-sm btn-secondary" id="reportNextPage" onclick="goToReportPage('next')">
下一页 <i class="fas fa-angle-right"></i>
</button>
<button class="btn btn-sm btn-secondary" id="reportLastPage" onclick="goToReportPage('last')">
末页 <i class="fas fa-angle-double-right"></i>
</button>
</div>
</div>
</div>
</div>
</section>
<!-- 爬虫控制页面 -->
<section id="crawler-control-section" class="content-section">
<div class="control-panel">
<div class="panel-header">
<h2><i class="fas fa-cogs"></i> 爬虫控制面板</h2>
</div>
<div class="panel-content">
<div class="control-group">
<h3>价格数据爬虫</h3>
<div class="control-buttons">
<button class="btn btn-success" onclick="startCrawler()">
<i class="fas fa-play"></i> 启动价格爬虫
</button>
<button class="btn btn-danger" onclick="stopCrawler()">
<i class="fas fa-stop"></i> 停止价格爬虫
</button>
<button class="btn btn-info" onclick="getCrawlerStatus()">
<i class="fas fa-info-circle"></i> 价格爬虫状态
</button>
</div>
</div>
<div class="control-group">
<h3>分析报告爬虫</h3>
<div class="control-buttons">
<button class="btn btn-success" onclick="startReportCrawler()">
<i class="fas fa-file-alt"></i> 启动报告爬虫
</button>
<button class="btn btn-danger" onclick="stopReportCrawler()">
<i class="fas fa-stop"></i> 停止报告爬虫
</button>
<button class="btn btn-info" onclick="getReportCrawlerStatus()">
<i class="fas fa-info-circle"></i> 报告爬虫状态
</button>
</div>
<!-- 立即爬取选项 -->
<div class="crawl-options">
<h4>立即爬取报告</h4>
<div class="form-group">
<label>
<input type="checkbox" id="fullCrawlMode" checked>
完整爬取模式(爬取所有历史数据)
</label>
<small class="help-text">
勾选:爬取所有可用的历史报告数据<br>
不勾选:只爬取最新的报告数据
</small>
</div>
<div class="control-buttons">
<button class="btn btn-primary" onclick="crawlReportsOnce()">
<i class="fas fa-download"></i> 开始爬取
</button>
</div>
</div>
</div>
</div>
</div>
</section>
<!-- 系统设置页面 -->
<section id="settings-section" class="content-section">
<div class="settings-panel">
<div class="panel-header">
<h2><i class="fas fa-cog"></i> 系统设置</h2>
</div>
<div class="panel-content">
<div class="settings-group">
<h3>爬虫配置</h3>
<div class="setting-item">
<label>爬取间隔(分钟)</label>
<input type="number" value="30" min="5" max="1440">
</div>
<div class="setting-item">
<label>超时时间(秒)</label>
<input type="number" value="30" min="10" max="300">
</div>
<div class="setting-item">
<label>重试次数</label>
<input type="number" value="3" min="1" max="10">
</div>
</div>
<div class="settings-group">
<h3>数据管理</h3>
<div class="setting-item">
<label>数据保留天数</label>
<input type="number" value="30" min="1" max="365">
</div>
<div class="setting-item">
<label>自动备份</label>
<input type="checkbox" checked>
</div>
</div>
<div class="settings-actions">
<button class="btn btn-primary">
<i class="fas fa-save"></i> 保存设置
</button>
<button class="btn btn-secondary">
<i class="fas fa-undo"></i> 重置
</button>
</div>
</div>
</div>
</section>
</div>
</main>
<!-- 报告详情模态框 -->
<div id="reportModal" class="modal hidden">
<div class="modal-content">
<div class="modal-header">
<h2 id="modalReportTitle">报告详情</h2>
<button class="modal-close" onclick="closeReportModal()">
<i class="fas fa-times"></i>
</button>
</div>
<div class="modal-body">
<div class="report-meta">
<div class="meta-item">
<label>报告类型:</label>
<span id="modalReportType">-</span>
</div>
<div class="meta-item">
<label>发布时间:</label>
<span id="modalReportDate">-</span>
</div>
<div class="meta-item">
<label>来源:</label>
<span id="modalReportSource">-</span>
</div>
</div>
<div class="report-content">
<div class="content-section">
<h3>总体结论</h3>
<div id="modalReportConclusion" class="content-text">-</div>
</div>
<div class="content-section">
<h3>畜产品价格</h3>
<div id="modalAnimalConclusion" class="content-text">-</div>
</div>
<div class="content-section">
<h3>水产品价格</h3>
<div id="modalAquaticConclusion" class="content-text">-</div>
</div>
<div class="content-section">
<h3>蔬菜价格</h3>
<div id="modalVegetablesConclusion" class="content-text">-</div>
</div>
<div class="content-section">
<h3>水果价格</h3>
<div id="modalFruitsConclusion" class="content-text">-</div>
</div>
<div class="content-section">
<h3>价格指数</h3>
<div id="modalIndexConclusion" class="content-text">-</div>
</div>
<div class="content-section">
<h3>涨跌幅分析</h3>
<div id="modalIncOrReduRange" class="content-text">-</div>
</div>
<div class="content-section">
<h3>完整内容</h3>
<div id="modalReportContent" class="content-html">-</div>
</div>
</div>
</div>
<div class="modal-footer">
<button class="btn btn-secondary" onclick="closeReportModal()">
<i class="fas fa-times"></i> 关闭
</button>
<button class="btn btn-primary" onclick="printReport()">
<i class="fas fa-print"></i> 打印
</button>
<button class="btn btn-success" onclick="exportCurrentReport()">
<i class="fas fa-download"></i> 导出
</button>
</div>
</div>
</div>
<!-- 加载提示 -->
<div id="loading" class="loading hidden">
<div class="loading-content">
<div class="spinner"></div>
<p>加载中...</p>
</div>
</div>
<!-- 消息提示 -->
<div id="message" class="message hidden">
<div class="message-content">
<span class="message-text"></span>
<button class="message-close" onclick="hideMessage()">×</button>
</div>
</div>
</div>
<script src="/static/js/app.js"></script>
</body>
</html>
|
2301_78526554/agricultural-platform
|
static/index.html
|
HTML
|
unknown
| 34,469
|
// 农产品市场价格管理平台 - 前端JavaScript
class MarketPlatform {
constructor() {
this.apiBase = '/api';
this.currentData = [];
this.currentReports = [];
this.currentSection = 'dashboard';
this.currentReportData = null;
this.charts = {};
this.currentTimeRange = 30; // 默认30天
this.currentReportPage = 1;
this.reportPageSize = 10;
this.totalReportPages = 0;
this.currentReportType = 'all'; // 当前报告类型
this.dashboardData = null; // 仪表盘数据
this.previewChart = null; // 预览图表
this.init();
}
async init() {
console.log('🚀 农产品市场价格管理平台初始化中...');
// 绑定事件
this.bindEvents();
// 初始化侧边栏
this.initSidebar();
// 加载初始数据
await this.loadInitialData();
console.log('✅ 平台初始化完成');
}
initSidebar() {
// 设置默认激活的导航项
this.showSection('dashboard');
}
bindEvents() {
// 搜索表单提交
const searchForm = document.getElementById('searchForm');
if (searchForm) {
searchForm.addEventListener('submit', (e) => {
e.preventDefault();
this.searchData();
});
}
// 定时刷新数据
setInterval(() => {
this.refreshStats();
}, 30000); // 30秒刷新一次统计数据
}
async loadInitialData() {
try {
// 加载统计数据
await this.refreshStats();
// 加载下拉选项
await this.loadDropdownOptions();
// 加载最新数据
await this.loadLatestData();
// 加载最新报告
await this.loadLatestReports();
// 加载报告统计信息
await this.loadReportStats();
// 加载仪表盘数据
await this.loadDashboardData();
} catch (error) {
console.error('加载初始数据失败:', error);
this.showMessage('加载数据失败,请刷新页面重试', 'error');
}
}
async refreshStats() {
try {
const response = await fetch(`${this.apiBase}/stats`);
const result = await response.json();
if (result.success) {
this.updateStatsDisplay(result.data);
}
} catch (error) {
console.error('刷新统计数据失败:', error);
}
}
updateStatsDisplay(data) {
const { data_stats, crawler_status } = data;
// 更新统计卡片
this.updateElement('totalRecords', data_stats?.total_records || 0);
this.updateElement('totalMarkets', data_stats?.total_markets || 0);
this.updateElement('totalVarieties', data_stats?.total_varieties || 0);
this.updateElement('crawlerStatus', crawler_status?.status || '未知');
}
updateElement(id, value) {
const element = document.getElementById(id);
if (element) {
element.textContent = value;
}
}
async loadDropdownOptions() {
try {
// 加载省份选项
const provincesResponse = await fetch(`${this.apiBase}/data/provinces`);
const provincesResult = await provincesResponse.json();
if (provincesResult.success) {
this.populateSelect('province', provincesResult.data);
}
// 加载品种选项
const varietiesResponse = await fetch(`${this.apiBase}/data/varieties`);
const varietiesResult = await varietiesResponse.json();
if (varietiesResult.success) {
this.populateSelect('variety', varietiesResult.data);
}
// 加载市场选项
const marketsResponse = await fetch(`${this.apiBase}/data/markets`);
const marketsResult = await marketsResponse.json();
if (marketsResult.success) {
this.populateSelect('market', marketsResult.data);
}
} catch (error) {
console.error('加载下拉选项失败:', error);
}
}
populateSelect(selectId, options) {
const select = document.getElementById(selectId);
if (!select) return;
// 清空现有选项(保留第一个默认选项)
const firstOption = select.firstElementChild;
select.innerHTML = '';
if (firstOption) {
select.appendChild(firstOption);
}
// 添加新选项
options.forEach(option => {
const optionElement = document.createElement('option');
optionElement.value = option;
optionElement.textContent = option;
select.appendChild(optionElement);
});
}
async loadLatestData() {
try {
this.showLoading(true);
const response = await fetch(`${this.apiBase}/data/latest?limit=100`);
const result = await response.json();
if (result.success) {
this.currentData = result.data;
this.displayData(result.data);
this.updateDataCount(result.count);
} else {
this.showMessage('加载数据失败', 'error');
}
} catch (error) {
console.error('加载最新数据失败:', error);
this.showMessage('网络错误,请检查连接', 'error');
} finally {
this.showLoading(false);
}
}
async searchData() {
try {
this.showLoading(true);
const formData = new FormData(document.getElementById('searchForm'));
const searchParams = Object.fromEntries(formData.entries());
// 移除空值
Object.keys(searchParams).forEach(key => {
if (!searchParams[key]) {
delete searchParams[key];
}
});
const response = await fetch(`${this.apiBase}/search`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(searchParams)
});
const result = await response.json();
if (result.success) {
this.currentData = result.data;
this.displayData(result.data);
this.updateDataCount(result.count);
this.showMessage(`搜索完成,找到 ${result.count} 条记录`, 'success');
} else {
this.showMessage('搜索失败', 'error');
}
} catch (error) {
console.error('搜索数据失败:', error);
this.showMessage('搜索出错,请重试', 'error');
} finally {
this.showLoading(false);
}
}
displayData(data) {
const tbody = document.getElementById('dataTableBody');
if (!tbody) return;
if (!data || data.length === 0) {
tbody.innerHTML = '<tr><td colspan="9" class="no-data">暂无数据</td></tr>';
return;
}
tbody.innerHTML = data.map(item => `
<tr>
<td>${item.省份 || item.province || '-'}</td>
<td>${item.市场名称 || item.market_name || '-'}</td>
<td>${item.品种名称 || item.variety_name || '-'}</td>
<td>${item.最低价 || item.min_price || '-'}</td>
<td>${item.平均价 || item.avg_price || '-'}</td>
<td>${item.最高价 || item.max_price || '-'}</td>
<td>${item.单位 || item.unit || '-'}</td>
<td>${item.交易日期 || item.trade_date || '-'}</td>
<td>${item.更新时间 || item.crawl_time || '-'}</td>
</tr>
`).join('');
}
updateDataCount(count) {
const countElement = document.getElementById('dataCount');
if (countElement) {
countElement.textContent = `共 ${count} 条记录`;
}
}
async startCrawler() {
try {
this.showLoading(true);
const response = await fetch(`${this.apiBase}/crawler/start`, {
method: 'POST'
});
const result = await response.json();
if (result.success) {
this.showMessage('爬虫启动成功', 'success');
setTimeout(() => this.refreshStats(), 2000);
} else {
this.showMessage('爬虫启动失败', 'error');
}
} catch (error) {
console.error('启动爬虫失败:', error);
this.showMessage('启动爬虫出错', 'error');
} finally {
this.showLoading(false);
}
}
async stopCrawler() {
try {
this.showLoading(true);
const response = await fetch(`${this.apiBase}/crawler/stop`, {
method: 'POST'
});
const result = await response.json();
if (result.success) {
this.showMessage('爬虫停止成功', 'success');
setTimeout(() => this.refreshStats(), 2000);
} else {
this.showMessage('爬虫停止失败', 'error');
}
} catch (error) {
console.error('停止爬虫失败:', error);
this.showMessage('停止爬虫出错', 'error');
} finally {
this.showLoading(false);
}
}
async getCrawlerStatus() {
try {
const response = await fetch(`${this.apiBase}/crawler/status`);
const result = await response.json();
if (result.success) {
const status = result.data;
const message = `爬虫状态: ${status.status}\n运行时间: ${status.running_time || '未知'}\n已爬取: ${status.crawled_count || 0} 条数据`;
alert(message);
} else {
this.showMessage('获取状态失败', 'error');
}
} catch (error) {
console.error('获取爬虫状态失败:', error);
this.showMessage('获取状态出错', 'error');
}
}
async exportData() {
try {
this.showLoading(true);
// 构建导出参数
const formData = new FormData(document.getElementById('searchForm'));
const params = new URLSearchParams();
for (const [key, value] of formData.entries()) {
if (value) {
params.append(key, value);
}
}
const url = `${this.apiBase}/export/csv?${params.toString()}`;
// 创建下载链接
const link = document.createElement('a');
link.href = url;
link.download = `market_data_${new Date().toISOString().slice(0, 10)}.csv`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
this.showMessage('数据导出成功', 'success');
} catch (error) {
console.error('导出数据失败:', error);
this.showMessage('导出数据出错', 'error');
} finally {
this.showLoading(false);
}
}
showLoading(show) {
const loading = document.getElementById('loading');
if (loading) {
loading.classList.toggle('hidden', !show);
}
}
showMessage(text, type = 'info') {
const message = document.getElementById('message');
const messageText = message?.querySelector('.message-text');
if (message && messageText) {
messageText.textContent = text;
message.classList.remove('hidden');
// 3秒后自动隐藏
setTimeout(() => {
message.classList.add('hidden');
}, 3000);
}
}
hideMessage() {
const message = document.getElementById('message');
if (message) {
message.classList.add('hidden');
}
}
// 报告相关方法
async loadLatestReports(page = 1, reportType = 'all') {
try {
const response = await fetch(`${this.apiBase}/reports/latest?limit=${this.reportPageSize}&page=${page}&report_type=${reportType}`);
const result = await response.json();
if (result.success) {
this.displayReports(result.data);
this.updateReportPagination(result);
this.updateReportCount(result.total);
this.updateReportTypeStats(result);
this.currentReportPage = page;
this.totalReportPages = result.total_pages;
this.currentReportType = reportType;
} else {
this.showMessage('加载报告失败', 'error');
}
} catch (error) {
console.error('加载报告失败:', error);
// 不显示错误消息,因为可能还没有报告数据
}
}
async loadReportStats() {
try {
const response = await fetch(`${this.apiBase}/reports/stats`);
const result = await response.json();
this.updateReportTypeStats(result);
} catch (error) {
console.error('加载报告统计失败:', error);
}
}
updateReportTypeStats(stats) {
// 更新报告类型统计信息
this.updateElement('totalReportsCount', stats.total || 0);
this.updateElement('dailyReportsCount', stats.daily_count || 0);
this.updateElement('monthlyReportsCount', stats.monthly_count || 0);
this.updateElement('yearlyReportsCount', stats.yearly_count || 0);
}
// 切换报告类型
switchReportType(reportType) {
this.currentReportType = reportType;
this.currentReportPage = 1; // 重置到第一页
this.loadLatestReports(1, reportType);
// 更新按钮状态
document.querySelectorAll('.report-type-btn').forEach(btn => {
btn.classList.remove('active');
});
document.querySelector(`[data-report-type="${reportType}"]`)?.classList.add('active');
}
// 仪表盘相关方法
async loadDashboardData() {
try {
const response = await fetch(`${this.apiBase}/dashboard/data`);
const result = await response.json();
if (result.success) {
this.dashboardData = result.data;
this.updateDashboardPreview();
console.log('仪表盘数据加载成功:', this.dashboardData);
} else {
console.warn('仪表盘数据加载失败:', result.error);
}
} catch (error) {
console.error('加载仪表盘数据失败:', error);
}
}
updateDashboardPreview() {
if (!this.dashboardData) return;
try {
// 更新价格指数
const priceIndexData = this.dashboardData.price_index_trend || [];
if (priceIndexData.length > 0) {
const latest = priceIndexData[priceIndexData.length - 1];
const previous = priceIndexData.length > 1 ? priceIndexData[priceIndexData.length - 2] : null;
this.updateElement('dashboardPriceIndex', latest.price_index_200.toFixed(2));
if (previous) {
const change = latest.price_index_200 - previous.price_index_200;
const changeElement = document.getElementById('dashboardPriceIndexChange');
if (changeElement) {
changeElement.textContent = `${change >= 0 ? '+' : ''}${change.toFixed(2)}`;
changeElement.className = `metric-change ${change >= 0 ? 'positive' : 'negative'}`;
}
}
}
// 更新蔬菜价格
const vegetableData = this.dashboardData.category_price_trends?.vegetables || [];
if (vegetableData.length > 0) {
const latest = vegetableData[vegetableData.length - 1];
this.updateElement('dashboardVegPrice', `${latest.avg_price.toFixed(2)} 元/公斤`);
const changeElement = document.getElementById('dashboardVegChange');
if (changeElement) {
changeElement.textContent = `${latest.change_rate >= 0 ? '+' : ''}${latest.change_rate.toFixed(1)}%`;
changeElement.className = `metric-change ${latest.change_rate >= 0 ? 'positive' : 'negative'}`;
}
}
// 更新水果价格
const fruitData = this.dashboardData.category_price_trends?.fruits || [];
if (fruitData.length > 0) {
const latest = fruitData[fruitData.length - 1];
this.updateElement('dashboardFruitPrice', `${latest.avg_price.toFixed(2)} 元/公斤`);
const changeElement = document.getElementById('dashboardFruitChange');
if (changeElement) {
changeElement.textContent = `${latest.change_rate >= 0 ? '+' : ''}${latest.change_rate.toFixed(1)}%`;
changeElement.className = `metric-change ${latest.change_rate >= 0 ? 'positive' : 'negative'}`;
}
}
// 更新猪肉价格
const meatData = this.dashboardData.category_price_trends?.meat || [];
if (meatData.length > 0) {
const latest = meatData[meatData.length - 1];
this.updateElement('dashboardMeatPrice', `${latest.avg_price.toFixed(2)} 元/公斤`);
const changeElement = document.getElementById('dashboardMeatChange');
if (changeElement) {
changeElement.textContent = `${latest.change_rate >= 0 ? '+' : ''}${latest.change_rate.toFixed(1)}%`;
changeElement.className = `metric-change ${latest.change_rate >= 0 ? 'positive' : 'negative'}`;
}
}
// 更新摘要信息
const summary = this.dashboardData.market_summary || {};
if (summary.date_range) {
const dateRange = `${this.formatDate(summary.date_range.start)} 至 ${this.formatDate(summary.date_range.end)}`;
this.updateElement('dashboardDateRange', dateRange);
}
if (summary.total_reports) {
this.updateElement('dashboardTotalReports', `${summary.total_reports} 篇`);
}
this.updateElement('dashboardLastUpdate', new Date().toLocaleString('zh-CN'));
// 更新预览图表
this.updatePreviewChart();
} catch (error) {
console.error('更新仪表盘预览失败:', error);
}
}
updatePreviewChart() {
const canvas = document.getElementById('previewChart');
if (!canvas || !this.dashboardData) return;
const ctx = canvas.getContext('2d');
const priceIndexData = this.dashboardData.price_index_trend || [];
if (priceIndexData.length === 0) return;
// 销毁现有图表
if (this.previewChart) {
this.previewChart.destroy();
}
const labels = priceIndexData.map(item => this.formatDate(item.date));
const data = priceIndexData.map(item => item.price_index_200);
this.previewChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: '农产品批发价格200指数',
data: data,
borderColor: '#007bff',
backgroundColor: 'rgba(0, 123, 255, 0.1)',
borderWidth: 2,
fill: true,
tension: 0.4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
display: false
}
},
scales: {
x: {
display: true,
grid: {
display: false
}
},
y: {
display: true,
grid: {
color: 'rgba(0, 0, 0, 0.1)'
}
}
}
}
});
}
formatDate(dateString) {
if (!dateString) return '';
try {
const date = new Date(dateString);
return date.toLocaleDateString('zh-CN', {
month: '2-digit',
day: '2-digit'
});
} catch (error) {
return dateString;
}
}
updateReportPagination(result) {
const pagination = document.getElementById('reportPagination');
if (!pagination) return;
if (result.total_pages <= 1) {
pagination.classList.add('hidden');
return;
}
pagination.classList.remove('hidden');
// 更新分页信息
this.updateElement('reportPageInfo', `第 ${result.page} 页,共 ${result.total_pages} 页`);
this.updateElement('reportTotalInfo', `总计 ${result.total} 条记录`);
// 更新按钮状态
const firstBtn = document.getElementById('reportFirstPage');
const prevBtn = document.getElementById('reportPrevPage');
const nextBtn = document.getElementById('reportNextPage');
const lastBtn = document.getElementById('reportLastPage');
if (firstBtn) firstBtn.disabled = result.page <= 1;
if (prevBtn) prevBtn.disabled = result.page <= 1;
if (nextBtn) nextBtn.disabled = result.page >= result.total_pages;
if (lastBtn) lastBtn.disabled = result.page >= result.total_pages;
// 生成页码
this.generateReportPageNumbers(result.page, result.total_pages);
}
generateReportPageNumbers(currentPage, totalPages) {
const container = document.getElementById('reportPageNumbers');
if (!container) return;
let html = '';
const maxVisible = 5;
let start = Math.max(1, currentPage - Math.floor(maxVisible / 2));
let end = Math.min(totalPages, start + maxVisible - 1);
if (end - start + 1 < maxVisible) {
start = Math.max(1, end - maxVisible + 1);
}
for (let i = start; i <= end; i++) {
const isActive = i === currentPage;
html += `<button class="page-number ${isActive ? 'active' : ''}" onclick="goToReportPage(${i})">${i}</button>`;
}
container.innerHTML = html;
}
goToReportPage(page) {
if (typeof page === 'string') {
if (page === 'prev') {
page = Math.max(1, this.currentReportPage - 1);
} else if (page === 'next') {
page = Math.min(this.totalReportPages, this.currentReportPage + 1);
} else if (page === 'last') {
page = this.totalReportPages;
}
}
if (page !== this.currentReportPage && page >= 1 && page <= this.totalReportPages) {
this.loadLatestReports(page, this.currentReportType);
}
}
displayReports(reports) {
const tbody = document.getElementById('reportTableBody');
if (!tbody) return;
if (!reports || reports.length === 0) {
tbody.innerHTML = '<tr><td colspan="6" class="no-data">暂无报告数据</td></tr>';
return;
}
// 保存当前报告数据
this.currentReports = reports;
tbody.innerHTML = reports.map((report, index) => `
<tr>
<td title="${report.报告标题 || ''}">${this.truncateText(report.报告标题 || '-', 50)}</td>
<td>${report.报告类型 || '-'}</td>
<td>${report.日报日期 || report.发布时间 || '-'}</td>
<td>${report.来源 || '-'}</td>
<td>${report.爬取时间 || '-'}</td>
<td>
<button class="btn btn-sm btn-info" onclick="viewReportDetail(${index})">
<i class="fas fa-eye"></i> 查看
</button>
</td>
</tr>
`).join('');
}
// 侧边栏导航功能
showSection(sectionName) {
// 隐藏所有section
const sections = document.querySelectorAll('.content-section');
sections.forEach(section => {
section.classList.remove('active');
});
// 显示目标section
const targetSection = document.getElementById(`${sectionName}-section`);
if (targetSection) {
targetSection.classList.add('active');
}
// 更新导航状态
const navLinks = document.querySelectorAll('.nav-link');
navLinks.forEach(link => {
link.classList.remove('active');
});
const activeLink = document.querySelector(`[onclick="showSection('${sectionName}')"]`);
if (activeLink) {
activeLink.classList.add('active');
}
// 更新页面标题
const titles = {
'dashboard': '数据概览',
'trends': '趋势仪表板',
'price-data': '价格数据',
'reports': '分析报告',
'crawler-control': '爬虫控制',
'settings': '系统设置'
};
const pageTitle = document.getElementById('pageTitle');
if (pageTitle) {
pageTitle.textContent = titles[sectionName] || '农产品平台';
}
this.currentSection = sectionName;
// 根据不同section加载相应数据
if (sectionName === 'price-data') {
this.loadLatestData();
} else if (sectionName === 'reports') {
this.loadLatestReports();
} else if (sectionName === 'trends') {
this.loadTrendsData();
}
}
// 侧边栏切换
toggleSidebar() {
const sidebar = document.getElementById('sidebar');
const mainContent = document.querySelector('.main-content');
if (window.innerWidth <= 768) {
// 移动端:显示/隐藏侧边栏
sidebar.classList.toggle('show');
} else {
// 桌面端:收缩/展开
sidebar.classList.toggle('collapsed');
mainContent.classList.toggle('expanded');
}
}
// 报告详情查看
viewReportDetail(reportIndex) {
if (!this.currentReports || !this.currentReports[reportIndex]) {
this.showMessage('报告数据不存在', 'error');
return;
}
const report = this.currentReports[reportIndex];
this.currentReportData = report;
// 填充模态框数据
this.populateReportModal(report);
// 显示模态框
const modal = document.getElementById('reportModal');
if (modal) {
modal.classList.remove('hidden');
}
}
populateReportModal(report) {
// 基本信息
this.setElementText('modalReportTitle', report.报告标题 || '未知报告');
this.setElementText('modalReportType', report.报告类型 || '-');
this.setElementText('modalReportDate', report.日报日期 || report.发布时间 || '-');
this.setElementText('modalReportSource', report.来源 || '-');
// 详细内容
this.setElementText('modalReportConclusion', report.总体结论 || '-');
this.setElementText('modalAnimalConclusion', report.畜产品结论 || '-');
this.setElementText('modalAquaticConclusion', report.水产品结论 || '-');
this.setElementText('modalVegetablesConclusion', report.蔬菜结论 || '-');
this.setElementText('modalFruitsConclusion', report.水果结论 || '-');
this.setElementText('modalIndexConclusion', report.价格指数结论 || '-');
this.setElementText('modalIncOrReduRange', report.涨跌幅分析 || '-');
// HTML内容
const contentElement = document.getElementById('modalReportContent');
if (contentElement) {
contentElement.innerHTML = report.报告内容 || report.纯文本内容 || '-';
}
}
setElementText(elementId, text) {
const element = document.getElementById(elementId);
if (element) {
element.textContent = text;
}
}
closeReportModal() {
const modal = document.getElementById('reportModal');
if (modal) {
modal.classList.add('hidden');
}
}
// 刷新当前section的数据
refreshCurrentSection() {
switch (this.currentSection) {
case 'dashboard':
this.refreshStats();
break;
case 'price-data':
this.loadLatestData();
break;
case 'reports':
this.loadLatestReports();
break;
default:
this.refreshStats();
}
}
// 导出当前section的数据
exportCurrentData() {
switch (this.currentSection) {
case 'price-data':
this.exportData();
break;
case 'reports':
this.exportReports();
break;
default:
this.exportData();
}
}
// 打印报告
printReport() {
if (!this.currentReportData) {
this.showMessage('没有可打印的报告', 'error');
return;
}
// 创建打印窗口
const printWindow = window.open('', '_blank');
const reportHtml = this.generatePrintableReport(this.currentReportData);
printWindow.document.write(reportHtml);
printWindow.document.close();
printWindow.print();
}
generatePrintableReport(report) {
return `
<!DOCTYPE html>
<html>
<head>
<title>${report.报告标题}</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; line-height: 1.6; }
h1 { color: #333; border-bottom: 2px solid #667eea; padding-bottom: 10px; }
h2 { color: #555; margin-top: 20px; }
.meta { background: #f5f5f5; padding: 15px; border-radius: 5px; margin-bottom: 20px; }
.content { margin-bottom: 15px; }
@media print { body { margin: 0; } }
</style>
</head>
<body>
<h1>${report.报告标题}</h1>
<div class="meta">
<p><strong>报告类型:</strong>${report.报告类型}</p>
<p><strong>发布时间:</strong>${report.日报日期 || report.发布时间}</p>
<p><strong>来源:</strong>${report.来源}</p>
</div>
<div class="content">
<h2>总体结论</h2>
<p>${report.总体结论}</p>
<h2>畜产品价格</h2>
<p>${report.畜产品结论}</p>
<h2>水产品价格</h2>
<p>${report.水产品结论}</p>
<h2>蔬菜价格</h2>
<p>${report.蔬菜结论}</p>
<h2>水果价格</h2>
<p>${report.水果结论}</p>
<h2>价格指数</h2>
<p>${report.价格指数结论}</p>
<h2>涨跌幅分析</h2>
<p>${report.涨跌幅分析}</p>
</div>
</body>
</html>
`;
}
// 导出当前报告
exportCurrentReport() {
if (!this.currentReportData) {
this.showMessage('没有可导出的报告', 'error');
return;
}
// 创建CSV内容
const csvContent = this.generateReportCSV(this.currentReportData);
// 下载文件
const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = `report_${this.currentReportData.报告ID || 'unknown'}_${new Date().toISOString().slice(0, 10)}.csv`;
link.click();
this.showMessage('报告导出成功', 'success');
}
generateReportCSV(report) {
const headers = ['字段', '内容'];
const rows = [
['报告标题', report.报告标题 || ''],
['报告类型', report.报告类型 || ''],
['发布时间', report.日报日期 || report.发布时间 || ''],
['来源', report.来源 || ''],
['总体结论', report.总体结论 || ''],
['畜产品结论', report.畜产品结论 || ''],
['水产品结论', report.水产品结论 || ''],
['蔬菜结论', report.蔬菜结论 || ''],
['水果结论', report.水果结论 || ''],
['价格指数结论', report.价格指数结论 || ''],
['涨跌幅分析', report.涨跌幅分析 || '']
];
const csvRows = [headers, ...rows];
return csvRows.map(row =>
row.map(field => `"${String(field).replace(/"/g, '""')}"`).join(',')
).join('\n');
}
// 仪表板相关方法
async loadTrendsData(days = null) {
try {
this.showLoading(true);
const timeRange = days || this.currentTimeRange;
const response = await fetch(`${this.apiBase}/dashboard/trends?days=${timeRange}`);
const result = await response.json();
if (result.success) {
this.updateMetrics(result.data.key_metrics);
this.updateCharts(result.data);
this.updateActivityData(result.data);
// 更新图表标题
this.updateChartTitle(result.data.time_range);
} else {
this.showMessage('加载趋势数据失败', 'error');
}
} catch (error) {
console.error('加载趋势数据失败:', error);
this.showMessage('网络错误,请检查连接', 'error');
} finally {
this.showLoading(false);
}
}
updateChartTitle(timeRange) {
const chartTitle = document.querySelector('#trends-section .chart-panel h2');
if (chartTitle) {
chartTitle.innerHTML = `<i class="fas fa-chart-line"></i> 价格趋势 (${timeRange})`;
}
}
changeTrendTimeRange() {
const select = document.getElementById('timeRangeSelect');
if (select) {
this.currentTimeRange = parseInt(select.value);
this.loadTrendsData(this.currentTimeRange);
}
}
updateMetrics(metrics) {
// 更新关键指标
this.updateElement('avgPrice', metrics.avg_price ? metrics.avg_price.toFixed(2) : '-');
this.updateElement('maxPrice', metrics.max_price ? metrics.max_price.toFixed(2) : '-');
this.updateElement('minPrice', metrics.min_price ? metrics.min_price.toFixed(2) : '-');
this.updateElement('totalReportsMetric', metrics.total_reports || 0);
this.updateElement('reportTypes', `${metrics.report_types || 0} 种类型`);
// 更新价格变化
const priceChangeElement = document.getElementById('priceChange');
if (priceChangeElement && metrics.price_change_percent !== undefined) {
const change = metrics.price_change_percent;
priceChangeElement.textContent = `${change > 0 ? '+' : ''}${change}%`;
priceChangeElement.className = `metric-change ${change >= 0 ? 'positive' : 'negative'}`;
}
}
updateCharts(data) {
// 销毁现有图表
Object.values(this.charts).forEach(chart => {
if (chart) chart.destroy();
});
this.charts = {};
// 创建价格趋势图
this.createPriceChart(data.price_trends);
// 创建报告分布图
this.createReportDistributionChart(data.report_trends);
// 创建报告趋势图
this.createReportTrendChart(data.report_trends);
}
createPriceChart(priceData) {
const ctx = document.getElementById('priceChart');
if (!ctx || !priceData || priceData.length === 0) return;
const labels = priceData.map(item => item.交易日期);
const prices = priceData.map(item => item.平均价);
this.charts.priceChart = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: '平均价格',
data: prices,
borderColor: '#667eea',
backgroundColor: 'rgba(102, 126, 234, 0.1)',
borderWidth: 2,
fill: true,
tension: 0.4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: false,
title: {
display: true,
text: '价格 (元/公斤)'
}
},
x: {
title: {
display: true,
text: '日期'
}
}
},
plugins: {
legend: {
display: false
}
}
}
});
}
createReportDistributionChart(reportData) {
const ctx = document.getElementById('reportChart');
if (!ctx || !reportData || !reportData.type_distribution) return;
const distribution = reportData.type_distribution;
const labels = Object.keys(distribution);
const values = Object.values(distribution);
this.charts.reportChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: labels,
datasets: [{
data: values,
backgroundColor: [
'#667eea',
'#764ba2',
'#f093fb',
'#f5576c',
'#4facfe',
'#00f2fe'
],
borderWidth: 2,
borderColor: '#fff'
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'bottom'
}
}
}
});
}
createReportTrendChart(reportData) {
const ctx = document.getElementById('reportTrendChart');
if (!ctx || !reportData || !reportData.daily_counts) return;
const dailyCounts = reportData.daily_counts;
const labels = dailyCounts.map(item => item.日期);
const counts = dailyCounts.map(item => item.报告数量);
this.charts.reportTrendChart = new Chart(ctx, {
type: 'bar',
data: {
labels: labels,
datasets: [{
label: '报告数量',
data: counts,
backgroundColor: 'rgba(102, 126, 234, 0.8)',
borderColor: '#667eea',
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
scales: {
y: {
beginAtZero: true,
title: {
display: true,
text: '报告数量'
}
},
x: {
title: {
display: true,
text: '日期'
}
}
},
plugins: {
legend: {
display: false
}
}
}
});
}
updateActivityData(data) {
// 更新活跃度数据
this.updateElement('activeMarkets', this.currentData ? new Set(this.currentData.map(item => item.市场名称 || item.market_name)).size : '-');
this.updateElement('monitoredVarieties', this.currentData ? new Set(this.currentData.map(item => item.品种名称 || item.variety_name)).size : '-');
this.updateElement('lastUpdate', data.last_update ? new Date(data.last_update).toLocaleString() : '-');
this.updateElement('coverageProvinces', this.currentData ? new Set(this.currentData.map(item => item.省份 || item.province)).size : '-');
}
refreshTrends() {
this.loadTrendsData();
}
truncateText(text, maxLength) {
if (!text || text.length <= maxLength) return text;
return text.substring(0, maxLength) + '...';
}
updateReportCount(count) {
const countElement = document.getElementById('reportCount');
if (countElement) {
countElement.textContent = `共 ${count} 篇报告`;
}
}
async startReportCrawler() {
try {
this.showLoading(true);
const response = await fetch(`${this.apiBase}/report-crawler/start`, {
method: 'POST'
});
const result = await response.json();
if (result.success) {
this.showMessage('报告爬虫启动成功', 'success');
} else {
this.showMessage('报告爬虫启动失败', 'error');
}
} catch (error) {
console.error('启动报告爬虫失败:', error);
this.showMessage('启动报告爬虫出错', 'error');
} finally {
this.showLoading(false);
}
}
async stopReportCrawler() {
try {
this.showLoading(true);
const response = await fetch(`${this.apiBase}/report-crawler/stop`, {
method: 'POST'
});
const result = await response.json();
if (result.success) {
this.showMessage('报告爬虫停止成功', 'success');
} else {
this.showMessage('报告爬虫停止失败', 'error');
}
} catch (error) {
console.error('停止报告爬虫失败:', error);
this.showMessage('停止报告爬虫出错', 'error');
} finally {
this.showLoading(false);
}
}
async getReportCrawlerStatus() {
try {
const response = await fetch(`${this.apiBase}/report-crawler/status`);
const result = await response.json();
if (result.success) {
const status = result.data;
const message = `报告爬虫状态: ${status.status}\n运行时间: ${status.running_time || '未知'}\n已爬取: ${status.crawled_count || 0} 篇报告\n报告类型: ${status.report_types || 0} 种`;
alert(message);
} else {
this.showMessage('获取报告爬虫状态失败', 'error');
}
} catch (error) {
console.error('获取报告爬虫状态失败:', error);
this.showMessage('获取状态出错', 'error');
}
}
async crawlReportsOnce() {
try {
this.showLoading(true);
// 获取完整爬取模式选项
const fullCrawlCheckbox = document.getElementById('fullCrawlMode');
const fullCrawl = fullCrawlCheckbox ? fullCrawlCheckbox.checked : true;
const crawlMode = fullCrawl ? '完整爬取' : '快速爬取';
// 确认对话框
if (fullCrawl) {
const confirmed = confirm(
'完整爬取模式将爬取所有可用的历史报告数据,可能需要较长时间。\n' +
'确定要继续吗?\n\n' +
'提示:如果只需要最新数据,可以取消勾选"完整爬取模式"。'
);
if (!confirmed) {
this.showLoading(false);
return;
}
}
const response = await fetch(`${this.apiBase}/report-crawler/crawl-once?full_crawl=${fullCrawl}`, {
method: 'POST'
});
const result = await response.json();
if (result.success) {
this.showMessage(`${result.message}`, 'success');
// 显示爬取提示
if (fullCrawl) {
this.showMessage(
'完整爬取已开始,请耐心等待。可以在控制台查看爬取进度。',
'info',
8000
);
} else {
// 快速爬取5秒后自动刷新报告列表
setTimeout(() => {
this.loadLatestReports();
}, 5000);
}
} else {
this.showMessage(result.message || '爬取失败', 'error');
}
} catch (error) {
console.error('执行报告爬取失败:', error);
this.showMessage('执行报告爬取出错', 'error');
} finally {
this.showLoading(false);
}
}
async exportReports() {
try {
this.showLoading(true);
const url = `${this.apiBase}/reports/export`;
// 创建下载链接
const link = document.createElement('a');
link.href = url;
link.download = `analysis_reports_${new Date().toISOString().slice(0, 10)}.csv`;
document.body.appendChild(link);
link.click();
document.body.removeChild(link);
this.showMessage('报告数据导出成功', 'success');
} catch (error) {
console.error('导出报告数据失败:', error);
this.showMessage('导出报告数据出错', 'error');
} finally {
this.showLoading(false);
}
}
}
// 全局函数(供HTML调用)
let platform;
// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', () => {
platform = new MarketPlatform();
});
// 全局函数
function refreshData() {
if (platform) {
platform.loadLatestData();
}
}
function exportData() {
if (platform) {
platform.exportData();
}
}
function startCrawler() {
if (platform) {
platform.startCrawler();
}
}
function stopCrawler() {
if (platform) {
platform.stopCrawler();
}
}
function getCrawlerStatus() {
if (platform) {
platform.getCrawlerStatus();
}
}
function resetSearch() {
const form = document.getElementById('searchForm');
if (form) {
form.reset();
if (platform) {
platform.loadLatestData();
}
}
}
function hideMessage() {
if (platform) {
platform.hideMessage();
}
}
// 报告相关全局函数
function startReportCrawler() {
if (platform) {
platform.startReportCrawler();
}
}
function stopReportCrawler() {
if (platform) {
platform.stopReportCrawler();
}
}
function getReportCrawlerStatus() {
if (platform) {
platform.getReportCrawlerStatus();
}
}
function crawlReportsOnce() {
if (platform) {
platform.crawlReportsOnce();
}
}
function refreshReports() {
if (platform) {
platform.loadLatestReports();
}
}
function exportReports() {
if (platform) {
platform.exportReports();
}
}
// 侧边栏导航全局函数
function showSection(sectionName) {
if (platform) {
platform.showSection(sectionName);
}
}
function toggleSidebar() {
if (platform) {
platform.toggleSidebar();
}
}
function refreshCurrentSection() {
if (platform) {
platform.refreshCurrentSection();
}
}
function exportCurrentData() {
if (platform) {
platform.exportCurrentData();
}
}
// 报告详情全局函数
function viewReportDetail(reportIndex) {
if (platform) {
platform.viewReportDetail(reportIndex);
}
}
function closeReportModal() {
if (platform) {
platform.closeReportModal();
}
}
function printReport() {
if (platform) {
platform.printReport();
}
}
function exportCurrentReport() {
if (platform) {
platform.exportCurrentReport();
}
}
// 仪表板全局函数
function refreshTrends() {
if (platform) {
platform.refreshTrends();
}
}
function changeTrendTimeRange() {
if (platform) {
platform.changeTrendTimeRange();
}
}
// 报告分页全局函数
function goToReportPage(page) {
if (platform) {
platform.goToReportPage(page);
}
}
// 切换报告类型全局函数
function switchReportType(reportType) {
if (platform) {
platform.switchReportType(reportType);
}
}
// 仪表盘全局函数
function openDashboard() {
window.open('/static/dashboard.html', '_blank');
}
function refreshDashboardData() {
if (platform) {
platform.loadDashboardData();
platform.showMessage('仪表盘数据已刷新', 'success');
}
}
// 窗口大小变化时调整侧边栏
window.addEventListener('resize', () => {
const sidebar = document.getElementById('sidebar');
const mainContent = document.querySelector('.main-content');
if (window.innerWidth > 768) {
// 桌面端:移除移动端的show类
sidebar.classList.remove('show');
}
});
// 点击模态框背景关闭
document.addEventListener('click', (e) => {
if (e.target.classList.contains('modal')) {
closeReportModal();
}
});
|
2301_78526554/agricultural-platform
|
static/js/app.js
|
JavaScript
|
unknown
| 51,195
|
/**
* 农产品市场价格管理平台 - 仪表盘
*/
class Dashboard {
constructor() {
this.apiBase = '/api';
this.charts = {};
this.dashboardData = null;
this.init();
}
async init() {
try {
this.showLoading(true);
await this.loadDashboardData();
this.initializeCharts();
this.updateOverviewCards();
this.updateSummary();
this.showLoading(false);
} catch (error) {
console.error('初始化仪表盘失败:', error);
this.showMessage('初始化仪表盘失败', 'error');
this.showLoading(false);
}
}
async refresh() {
try {
this.showLoading(true);
await this.loadDashboardData();
this.updateOverviewCards();
this.updateSummary();
// 更新图表数据
this.updatePriceIndexChart();
this.updateCategoryChart();
this.updateProductsChart();
this.updateVolatilityAnalysis();
this.showLoading(false);
this.showMessage('数据刷新成功', 'success');
} catch (error) {
console.error('刷新数据失败:', error);
this.showMessage('刷新数据失败', 'error');
this.showLoading(false);
}
}
async loadDashboardData() {
try {
const response = await fetch(`${this.apiBase}/dashboard/data`);
const result = await response.json();
if (result.success) {
this.dashboardData = result.data;
console.log('仪表盘数据加载成功:', this.dashboardData);
} else {
throw new Error(result.error || '加载数据失败');
}
} catch (error) {
console.error('加载仪表盘数据失败:', error);
throw error;
}
}
initializeCharts() {
this.initPriceIndexChart();
this.initCategoryChart();
this.initProductsChart();
this.updateVolatilityAnalysis();
}
initPriceIndexChart() {
const ctx = document.getElementById('priceIndexChart').getContext('2d');
const priceIndexData = this.dashboardData.price_index_trend || [];
const labels = priceIndexData.map(item => this.formatDate(item.date));
const priceIndex200 = priceIndexData.map(item => item.price_index_200);
const basketIndex = priceIndexData.map(item => item.basket_index);
this.charts.priceIndex = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [
{
label: '农产品批发价格200指数',
data: priceIndex200,
borderColor: '#007bff',
backgroundColor: 'rgba(0, 123, 255, 0.1)',
borderWidth: 2,
fill: true,
tension: 0.4
},
{
label: '菜篮子产品批发价格指数',
data: basketIndex,
borderColor: '#28a745',
backgroundColor: 'rgba(40, 167, 69, 0.1)',
borderWidth: 2,
fill: true,
tension: 0.4
}
]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
},
tooltip: {
mode: 'index',
intersect: false,
}
},
scales: {
x: {
display: true,
title: {
display: true,
text: '日期'
}
},
y: {
display: true,
title: {
display: true,
text: '指数'
}
}
},
interaction: {
mode: 'nearest',
axis: 'x',
intersect: false
}
}
});
}
initCategoryChart() {
const ctx = document.getElementById('categoryChart').getContext('2d');
const categoryData = this.dashboardData.category_price_trends || {};
// 默认显示蔬菜数据
const vegetableData = categoryData.vegetables || [];
const labels = vegetableData.map(item => this.formatDate(item.date));
const prices = vegetableData.map(item => item.avg_price);
this.charts.category = new Chart(ctx, {
type: 'line',
data: {
labels: labels,
datasets: [{
label: '蔬菜平均价格 (元/公斤)',
data: prices,
borderColor: '#28a745',
backgroundColor: 'rgba(40, 167, 69, 0.1)',
borderWidth: 2,
fill: true,
tension: 0.4
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
}
},
scales: {
x: {
display: true,
title: {
display: true,
text: '日期'
}
},
y: {
display: true,
title: {
display: true,
text: '价格 (元/公斤)'
}
}
}
}
});
}
initProductsChart() {
const ctx = document.getElementById('productsChart').getContext('2d');
const productsData = this.dashboardData.key_products_trends || {};
const datasets = [];
const colors = ['#007bff', '#28a745', '#ffc107', '#dc3545', '#6f42c1'];
let colorIndex = 0;
// 获取所有产品的最新价格
const latestPrices = [];
const productNames = [];
Object.keys(productsData).forEach(productName => {
const productTrend = productsData[productName];
if (productTrend && productTrend.length > 0) {
const latestData = productTrend[productTrend.length - 1];
productNames.push(productName);
latestPrices.push(latestData.price);
}
});
this.charts.products = new Chart(ctx, {
type: 'bar',
data: {
labels: productNames,
datasets: [{
label: '最新价格 (元/公斤)',
data: latestPrices,
backgroundColor: colors.slice(0, productNames.length),
borderColor: colors.slice(0, productNames.length),
borderWidth: 1
}]
},
options: {
responsive: true,
maintainAspectRatio: false,
plugins: {
legend: {
position: 'top',
}
},
scales: {
x: {
display: true,
title: {
display: true,
text: '产品'
}
},
y: {
display: true,
title: {
display: true,
text: '价格 (元/公斤)'
}
}
}
}
});
}
updateCategoryChart() {
const selectedCategory = document.getElementById('categorySelect').value;
const categoryData = this.dashboardData.category_price_trends || {};
if (selectedCategory === 'all') {
// 显示所有类别的对比
this.updateAllCategoriesChart();
} else {
// 显示单个类别的趋势
this.updateSingleCategoryChart(selectedCategory, categoryData);
}
}
updateAllCategoriesChart() {
const categoryData = this.dashboardData.category_price_trends || {};
const datasets = [];
const colors = {
vegetables: '#28a745',
fruits: '#ffc107',
meat: '#dc3545',
aquatic: '#17a2b8'
};
const labels = {
vegetables: '蔬菜',
fruits: '水果',
meat: '畜产品',
aquatic: '水产品'
};
// 获取最长的日期序列
let allDates = [];
Object.values(categoryData).forEach(data => {
if (data && data.length > 0) {
const dates = data.map(item => item.date);
allDates = [...new Set([...allDates, ...dates])].sort();
}
});
Object.keys(categoryData).forEach(category => {
const data = categoryData[category] || [];
if (data.length > 0) {
const prices = allDates.map(date => {
const item = data.find(d => d.date === date);
return item ? item.avg_price : null;
});
datasets.push({
label: labels[category] || category,
data: prices,
borderColor: colors[category] || '#6c757d',
backgroundColor: `${colors[category] || '#6c757d'}20`,
borderWidth: 2,
fill: false,
tension: 0.4
});
}
});
this.charts.category.data.labels = allDates.map(date => this.formatDate(date));
this.charts.category.data.datasets = datasets;
this.charts.category.update();
}
updateSingleCategoryChart(category, categoryData) {
const data = categoryData[category] || [];
const labels = data.map(item => this.formatDate(item.date));
const prices = data.map(item => item.avg_price);
const categoryLabels = {
vegetables: '蔬菜平均价格',
fruits: '水果平均价格',
meat: '畜产品价格',
aquatic: '水产品价格'
};
const categoryColors = {
vegetables: '#28a745',
fruits: '#ffc107',
meat: '#dc3545',
aquatic: '#17a2b8'
};
this.charts.category.data.labels = labels;
this.charts.category.data.datasets = [{
label: `${categoryLabels[category] || category} (元/公斤)`,
data: prices,
borderColor: categoryColors[category] || '#007bff',
backgroundColor: `${categoryColors[category] || '#007bff'}20`,
borderWidth: 2,
fill: true,
tension: 0.4
}];
this.charts.category.update();
}
// 更新图表数据的方法
updatePriceIndexChart() {
if (!this.charts.priceIndex || !this.dashboardData) return;
const priceIndexData = this.dashboardData.price_index_trend || [];
const labels = priceIndexData.map(item => this.formatDate(item.date));
const priceIndex200 = priceIndexData.map(item => item.price_index_200);
const basketIndex = priceIndexData.map(item => item.basket_index);
this.charts.priceIndex.data.labels = labels;
this.charts.priceIndex.data.datasets[0].data = priceIndex200;
this.charts.priceIndex.data.datasets[1].data = basketIndex;
this.charts.priceIndex.update();
}
updateProductsChart() {
if (!this.charts.products || !this.dashboardData) return;
const productsData = this.dashboardData.key_products || [];
const labels = productsData.map(item => item.product);
const prices = productsData.map(item => item.latest_price);
this.charts.products.data.labels = labels;
this.charts.products.data.datasets[0].data = prices;
this.charts.products.update();
}
updateVolatilityAnalysis() {
const volatilityData = this.dashboardData.volatility_analysis || {};
const topGainers = volatilityData.top_gainers || [];
const topLosers = volatilityData.top_losers || [];
// 更新涨幅前五
const gainersContainer = document.getElementById('topGainers');
gainersContainer.innerHTML = '';
// 获取最新的涨幅数据
const latestGainers = this.getLatestVolatilityData(topGainers, 5);
latestGainers.forEach(item => {
const div = document.createElement('div');
div.className = 'volatility-item';
div.innerHTML = `
<span class="product-name">${item.product}</span>
<span class="change-rate positive">+${item.change_rate.toFixed(1)}%</span>
`;
gainersContainer.appendChild(div);
});
// 更新跌幅前五
const losersContainer = document.getElementById('topLosers');
losersContainer.innerHTML = '';
const latestLosers = this.getLatestVolatilityData(topLosers, 5);
latestLosers.forEach(item => {
const div = document.createElement('div');
div.className = 'volatility-item';
div.innerHTML = `
<span class="product-name">${item.product}</span>
<span class="change-rate negative">${item.change_rate.toFixed(1)}%</span>
`;
losersContainer.appendChild(div);
});
}
getLatestVolatilityData(data, limit) {
if (!data || data.length === 0) return [];
// 按日期分组,获取最新日期的数据
const groupedByDate = {};
data.forEach(item => {
if (!groupedByDate[item.date]) {
groupedByDate[item.date] = [];
}
groupedByDate[item.date].push(item);
});
// 获取最新日期
const latestDate = Object.keys(groupedByDate).sort().pop();
const latestData = groupedByDate[latestDate] || [];
// 按变化幅度排序并取前N个
return latestData
.sort((a, b) => Math.abs(b.change_rate) - Math.abs(a.change_rate))
.slice(0, limit);
}
updateOverviewCards() {
try {
// 更新价格指数卡片
const priceIndexData = this.dashboardData.price_index_trend || [];
if (priceIndexData.length > 0) {
const latest = priceIndexData[priceIndexData.length - 1];
const previous = priceIndexData.length > 1 ? priceIndexData[priceIndexData.length - 2] : null;
this.animateNumber('latestPriceIndex', latest.price_index_200, 2);
if (previous) {
const change = latest.price_index_200 - previous.price_index_200;
const changeElement = document.getElementById('priceIndexChange');
changeElement.textContent = `${change >= 0 ? '+' : ''}${change.toFixed(2)}`;
changeElement.className = `metric-change ${change >= 0 ? 'positive' : 'negative'}`;
}
}
// 更新蔬菜价格卡片
const vegetableData = this.dashboardData.category_price_trends?.vegetables || [];
if (vegetableData.length > 0) {
const latest = vegetableData[vegetableData.length - 1];
this.animatePrice('latestVegPrice', latest.avg_price);
const changeElement = document.getElementById('vegPriceChange');
changeElement.textContent = `${latest.change_rate >= 0 ? '+' : ''}${latest.change_rate.toFixed(1)}%`;
changeElement.className = `metric-change ${latest.change_rate >= 0 ? 'positive' : 'negative'}`;
}
// 更新水果价格卡片
const fruitData = this.dashboardData.category_price_trends?.fruits || [];
if (fruitData.length > 0) {
const latest = fruitData[fruitData.length - 1];
this.animatePrice('latestFruitPrice', latest.avg_price);
const changeElement = document.getElementById('fruitPriceChange');
changeElement.textContent = `${latest.change_rate >= 0 ? '+' : ''}${latest.change_rate.toFixed(1)}%`;
changeElement.className = `metric-change ${latest.change_rate >= 0 ? 'positive' : 'negative'}`;
}
// 更新猪肉价格卡片
const meatData = this.dashboardData.category_price_trends?.meat || [];
if (meatData.length > 0) {
const latest = meatData[meatData.length - 1];
this.animatePrice('latestMeatPrice', latest.avg_price);
const changeElement = document.getElementById('meatPriceChange');
changeElement.textContent = `${latest.change_rate >= 0 ? '+' : ''}${latest.change_rate.toFixed(1)}%`;
changeElement.className = `metric-change ${latest.change_rate >= 0 ? 'positive' : 'negative'}`;
}
} catch (error) {
console.error('更新概览卡片失败:', error);
}
}
// 数字动画效果
animateNumber(elementId, targetValue, decimals = 0) {
const element = document.getElementById(elementId);
if (!element) return;
const startValue = 0;
const duration = 1500; // 1.5秒
const startTime = performance.now();
const animate = (currentTime) => {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
// 使用缓动函数
const easeOutQuart = 1 - Math.pow(1 - progress, 4);
const currentValue = startValue + (targetValue - startValue) * easeOutQuart;
element.textContent = currentValue.toFixed(decimals);
if (progress < 1) {
requestAnimationFrame(animate);
}
};
requestAnimationFrame(animate);
}
// 价格动画效果
animatePrice(elementId, targetValue) {
const element = document.getElementById(elementId);
if (!element) return;
const startValue = 0;
const duration = 1500;
const startTime = performance.now();
const animate = (currentTime) => {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
const easeOutQuart = 1 - Math.pow(1 - progress, 4);
const currentValue = startValue + (targetValue - startValue) * easeOutQuart;
element.textContent = `${currentValue.toFixed(2)} 元/公斤`;
if (progress < 1) {
requestAnimationFrame(animate);
}
};
requestAnimationFrame(animate);
}
updateSummary() {
try {
const summary = this.dashboardData.market_summary || {};
// 更新日期范围
if (summary.date_range) {
const dateRange = `${this.formatDate(summary.date_range.start)} 至 ${this.formatDate(summary.date_range.end)}`;
document.getElementById('dateRange').textContent = dateRange;
}
// 更新报告总数
if (summary.total_reports) {
document.getElementById('totalReports').textContent = `${summary.total_reports} 篇`;
}
// 更新最后更新时间
document.getElementById('lastUpdate').textContent = new Date().toLocaleString('zh-CN');
} catch (error) {
console.error('更新摘要信息失败:', error);
}
}
async refreshChart(chartType) {
try {
this.showLoading(true);
await this.loadDashboardData();
switch (chartType) {
case 'priceIndex':
this.charts.priceIndex.destroy();
this.initPriceIndexChart();
break;
case 'category':
this.charts.category.destroy();
this.initCategoryChart();
this.updateCategoryChart();
break;
case 'products':
this.charts.products.destroy();
this.initProductsChart();
break;
case 'volatility':
this.updateVolatilityAnalysis();
break;
}
this.updateOverviewCards();
this.updateSummary();
this.showMessage('图表已刷新', 'success');
} catch (error) {
console.error('刷新图表失败:', error);
this.showMessage('刷新图表失败', 'error');
} finally {
this.showLoading(false);
}
}
formatDate(dateString) {
if (!dateString) return '';
try {
const date = new Date(dateString);
return date.toLocaleDateString('zh-CN', {
month: '2-digit',
day: '2-digit'
});
} catch (error) {
return dateString;
}
}
showLoading(show) {
const loadingIndicator = document.getElementById('loadingIndicator');
if (loadingIndicator) {
loadingIndicator.style.display = show ? 'flex' : 'none';
}
}
showMessage(message, type = 'info', duration = 3000) {
const container = document.getElementById('messageContainer');
if (!container) return;
const messageDiv = document.createElement('div');
messageDiv.className = `message message-${type}`;
const icon = type === 'success' ? 'check-circle' :
type === 'error' ? 'exclamation-circle' :
type === 'warning' ? 'exclamation-triangle' : 'info-circle';
messageDiv.innerHTML = `
<i class="fas fa-${icon}"></i>
<span>${message}</span>
`;
container.appendChild(messageDiv);
// 自动移除消息
setTimeout(() => {
if (messageDiv.parentNode) {
messageDiv.parentNode.removeChild(messageDiv);
}
}, duration);
}
}
// 全局函数
function refreshChart(chartType) {
if (window.dashboard) {
window.dashboard.refreshChart(chartType);
}
}
function updateCategoryChart() {
if (window.dashboard) {
window.dashboard.updateCategoryChart();
}
}
// 全局刷新函数
function refreshDashboard() {
if (window.dashboard) {
window.dashboard.refresh();
}
}
// 初始化仪表盘
document.addEventListener('DOMContentLoaded', function() {
window.dashboard = new Dashboard();
});
|
2301_78526554/agricultural-platform
|
static/js/dashboard.js
|
JavaScript
|
unknown
| 23,586
|
from setuptools import setup, find_packages
setup(
name="compression_tool",
version="0.1",
packages=find_packages(),
install_requires=[
"tqdm",
],
entry_points={
'console_scripts': [
'my_tool = src.__main__:main',
],
},
)
|
2301_79074651/Huffman
|
setup.py
|
Python
|
mit
| 286
|
from .huffman import HuffmanTree as Huffman
from .huffman_extractor import HuffmanExtractor as Extractor
from .huffman_compressor import HuffmanCompressor as Compressor
__all__ = ["Huffman", "Extractor", "Compressor"]
|
2301_79074651/Huffman
|
src/__init__.py
|
Python
|
mit
| 218
|
import argparse
from tqdm import tqdm
from typing import List
from pathlib import Path
from src.huffman_extractor import HuffmanExtractor as Extractor
from src.huffman_compressor import HuffmanCompressor as Compressor
class CompressionTool:
def __init__(self, input_files: List[Path], output_dir: Path, action: str, overwrite: bool):
self.input_files = input_files
self.output_dir = output_dir
self.action = action
self.overwrite = overwrite
def _compress(self, file: Path, output_path: Path) -> None:
"""文件压缩"""
print(f"压缩文件:{file} -> {output_path}")
compressor = Compressor(file, output_path)
compressor.compress()
def _extract(self, file: Path, output_path: Path) -> None:
"""文件解压"""
print(f"解压文件:{file} -> {output_path}")
extractor = Extractor(file, output_path)
extractor.extract()
def process_files(self) -> None:
"""处理输入文件,根据模式进行压缩或解压"""
if not self.output_dir.exists():
print(f"创建输出目录:{self.output_dir}")
self.output_dir.mkdir(parents=True)
# 使用 tqdm 创建进度条
with tqdm(total=len(self.input_files), desc="处理文件", unit="file") as pbar:
for file in self.input_files:
if not file.exists():
print(f"文件不存在,跳过:{file}")
pbar.update(1)
continue
if self.action == 'compress':
output_file = self.output_dir / f"compressed_{file.name}"
if output_file.exists() and not self.overwrite:
print(f"文件已存在,跳过:{output_file}")
pbar.update(1)
continue
self._compress(file, output_file)
elif self.action == 'extract':
output_file = self.output_dir / f"extracted_{file.name}"
if output_file.exists() and not self.overwrite:
print(f"文件已存在,跳过:{output_file}")
pbar.update(1)
continue
self._extract(file, output_file)
pbar.update(1)
def interact(self) -> None:
"""交互模式"""
while True:
print("\n请输入一个目录路径(或者输入exit退出):")
dir_path = input().strip()
if dir_path.lower() == 'exit':
print("退出交互模式")
break
dir_path = Path(dir_path)
if not dir_path.is_dir():
print(f"{dir_path} 不是有效的目录,请重新输入!")
continue
txt_files = list(dir_path.glob("*.txt"))
if not txt_files:
print("该目录下没有 .txt 文件。")
continue
print("\n可操作的文件:")
for idx, file in enumerate(txt_files, start=1):
print(f"{idx}. {file.name}")
print("\n请选择文件,输入文件的序号(多个序号用逗号分隔):")
selected_files_idx = input().strip()
selected_files_idx = selected_files_idx.split(',')
selected_files = []
for idx in selected_files_idx:
try:
selected_files.append(txt_files[int(idx.strip()) - 1])
except (ValueError, IndexError):
print(f"无效的序号:{idx}")
if not selected_files:
print("没有选择有效的文件,重新开始。")
continue
for file in selected_files:
print(f"\n请选择针对 {file.name} 的操作:1. 压缩 2. 解压")
action_choice = input().strip()
action = 'compress' if action_choice == '1' else 'extract'
print("\n请输入保存路径(包括文件名):")
save_path = input().strip()
save_path = Path(save_path)
if action == 'compress':
self._compress(file, save_path)
elif action == 'extract':
self._extract(file, save_path)
def main() -> None:
parser = argparse.ArgumentParser(
description="逐个文件压缩/解压工具",
epilog="示例:my_tool -c -i file1.txt file2.txt -o ./output -y"
)
# 操作模式
action_group = parser.add_mutually_exclusive_group()
action_group.add_argument('-c', '--compress', action='store_true', help="压缩模式")
action_group.add_argument('-x', '--extract', action='store_true', help="解压模式")
# 输入文件
parser.add_argument(
'-i', '--input',
nargs='+',
type=Path,
help="输入文件,支持多个文件"
)
# 输出路径
parser.add_argument(
'-o', '--output',
type=Path,
default=Path.cwd(),
help="输出路径(目录),默认为当前目录"
)
# 是否覆盖
overwrite_group = parser.add_mutually_exclusive_group()
overwrite_group.add_argument(
'-y', '--yes',
action='store_true',
help="覆盖已存在文件"
)
overwrite_group.add_argument(
'-n', '--no',
action='store_true',
help="禁止覆盖已存在文件"
)
# 交互模式
parser.add_argument(
'--interact',
action='store_true',
help="启用交互模式"
)
args = parser.parse_args()
# 选择覆盖逻辑
overwrite = args.yes or not args.no
action = 'compress' if args.compress else 'extract'
if args.interact:
tool = CompressionTool(
input_files=[],
output_dir=Path.cwd(),
action='compress',
overwrite=overwrite
)
tool.interact()
else:
tool = CompressionTool(
input_files=args.input,
output_dir=args.output,
action=action,
overwrite=overwrite
)
tool.process_files()
if __name__ == "__main__":
main()
|
2301_79074651/Huffman
|
src/__main__.py
|
Python
|
mit
| 6,297
|
import heapq
from typing import Dict, Optional
class HuffmanNode:
"""哈夫曼树的节点"""
def __init__(self, char: Optional[str], freq: int):
self.char = char
self.freq = freq
self.left = None
self.right = None
def __lt__(self, other):
"""用于优先队列比较,频率小的优先"""
return self.freq < other.freq
class HuffmanTree:
"""哈夫曼树类"""
def __init__(self):
self.root = None
self.codes = {}
def __str__(self) -> str:
"""返回哈夫曼树的编码字典字符串"""
if not self.codes:
self.get_codes()
return str(self.codes)
def _generate_codes(self, node: HuffmanNode, current_code: str) -> None:
"""递归生成编码字典"""
if not node:
return
if node.char is not None:
self.codes[node.char] = current_code
return
self._generate_codes(node.left, current_code + '0')
self._generate_codes(node.right, current_code + '1')
def build_tree(self, freq_dict: Dict[str, int]) -> None:
"""根据字频字典构建哈夫曼树
Args:
freq_dict (Dict[str, int]): 字频字典,其中键为字符,值为其出现的频率。
Returns:
None: 直接更新类的 `self.root` 属性,表示构建的哈夫曼树根节点。
"""
heap = [HuffmanNode(char, freq) for char, freq in freq_dict.items()]
heapq.heapify(heap)
while len(heap) > 1:
node1 = heapq.heappop(heap)
node2 = heapq.heappop(heap)
merged = HuffmanNode(None, node1.freq + node2.freq)
merged.left = node1
merged.right = node2
heapq.heappush(heap, merged)
self.root = heap[0] if heap else None
def get_codes(self) -> Dict[str, str]:
"""根据哈夫曼树生成编码字典"""
self.codes = {}
self._generate_codes(self.root, '')
return self.codes
if __name__ == "__main__":
freq_dict = {'a': 5, 'b': 9, 'c': 12, 'd': 13, 'e': 16, 'f': 45}
huffman_tree = HuffmanTree()
huffman_tree.build_tree(freq_dict)
print(huffman_tree)
|
2301_79074651/Huffman
|
src/huffman.py
|
Python
|
mit
| 2,238
|
import json
from typing import Dict
from pathlib import Path
from src.huffman import HuffmanTree
class HuffmanCompressor:
def __init__(self, input_path: Path, output_path: Path):
"""哈夫曼树解压器初始化函数
Args:
input_path (Path): 输入文件
output_path (Path): 输出文件
"""
self.input_path = input_path
self.output_path = output_path
self.tree = HuffmanTree()
def _get_frequency(self, content: str) -> Dict[str, int]:
"""根据文本内容生成字频字典
Args:
content (str): 文本内容
Returns:
Dict[str, int]: 生成的字频字典
"""
freq_dict = {}
for char in content:
freq_dict[char] = freq_dict.get(char, 0) + 1
return freq_dict
def _to_byte_array(self, bit_string: str) -> bytes:
"""将二进制序列转换为字节序列
Args:
bit_string (str): 二进制序列
Returns:
bytes: 生成的字节序列
"""
padding = 8 - len(bit_string) % 8
bit_string += '0' * padding
byte_data = bytearray()
for i in range(0, len(bit_string), 8):
byte_data.append(int(bit_string[i:i + 8], 2))
return bytes([padding]) + byte_data
def compress(self) -> None:
if not self.input_path.exists():
print(f"输入文件不存在:{self.input_path}")
return
with self.input_path.open('r', encoding='utf-8') as file:
content = file.read()
freq_dict = self._get_frequency(content)
self.tree.build_tree(freq_dict)
codes = self.tree.get_codes()
encoded_content = ''.join(codes[char] for char in content)
byte_data = self._to_byte_array(encoded_content)
with self.output_path.open('wb') as file:
json_metadata = json.dumps(freq_dict).encode('utf-8')
file.write(len(json_metadata).to_bytes(4, 'big'))
file.write(json_metadata)
file.write(byte_data)
print(f"压缩完成,保存至:{self.output_path}")
if __name__ == "__main__":
input_path = Path("HP.txt")
output_path = Path("compressed_HP.txt")
compressor = HuffmanCompressor(input_path, output_path)
compressor.compress()
|
2301_79074651/Huffman
|
src/huffman_compressor.py
|
Python
|
mit
| 2,362
|
import json
from typing import Dict
from pathlib import Path
from src.huffman import HuffmanTree
class HuffmanExtractor:
def __init__(self, input_path: Path, output_path: Path):
"""哈夫曼树解压器初始化函数
Args:
input_path (Path): 输入文件
output_path (Path): 输出文件
"""
self.input_path = input_path
self.output_path = output_path
self.tree = HuffmanTree()
def _read_metadata(self, file) -> Dict[str, int]:
"""读取压缩文件中的元数据(字频字典)
Args:
file: 已打开的文件对象
Returns:
Dict[str, int]: 解压需要的字频字典
"""
metadata_len = int.from_bytes(file.read(4), 'big')
metadata = file.read(metadata_len)
return json.loads(metadata.decode('utf-8'))
def _to_bit_string(self, byte_data: bytes) -> str:
"""将字节序列转换为二进制字符串
Args:
byte_data (bytes): 字节序列
Returns:
str: 转换后的二进制字符串
"""
padding = byte_data[0]
bit_string = ''.join(f'{byte:08b}' for byte in byte_data[1:])
return bit_string[:-padding] if padding else bit_string
def _decode(self, bit_string: str, codes: Dict[str, str]) -> str:
"""根据哈夫曼编码解码二进制字符串
Args:
bit_string (str): 二进制字符串
codes (Dict[str, str]): 哈夫曼编码字典
Returns:
str: 解码后的原始内容
"""
reverse_codes = {v: k for k, v in codes.items()}
current_code = ""
decoded_content = []
for bit in bit_string:
current_code += bit
if current_code in reverse_codes:
decoded_content.append(reverse_codes[current_code])
current_code = ""
return ''.join(decoded_content)
def extract(self) -> None:
if not self.input_path.exists():
print(f"输入文件不存在:{self.input_path}")
return
with self.input_path.open('rb') as file:
freq_dict = self._read_metadata(file)
self.tree.build_tree(freq_dict)
codes = self.tree.get_codes()
byte_data = file.read()
bit_string = self._to_bit_string(byte_data)
decoded_content = self._decode(bit_string, codes)
with self.output_path.open('w', encoding='utf-8') as file:
file.write(decoded_content)
print(f"解压完成,保存至:{self.output_path}")
if __name__ == "__main__":
input_path = Path("compressed_HP.txt")
output_path = Path("origin_HP.txt")
extractor = HuffmanExtractor(input_path, output_path)
extractor.extract()
|
2301_79074651/Huffman
|
src/huffman_extractor.py
|
Python
|
mit
| 2,843
|
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
int main()
{
printf("Hello World!!!");
return 0;
}
|
2301_77966824/first-meeting
|
09/09_18/09_18_01/09_18_01.c
|
C
|
unknown
| 104
|
#include <stdio.h>
#include <stdbool.h>
int main()
{
scanf();
printf("%zd\n", sizeof(char));
printf("%zd\n", sizeof(short));
printf("%zd\n", sizeof(int));
printf("%zd\n", sizeof(long));
printf("%zd\n", sizeof(long long));
printf("%zd\n", sizeof(float));
printf("%zd\n", sizeof(double));
printf("%zd\n", sizeof(long double));
printf("%zd\n", sizeof(bool));
return 0;
}
|
2301_77966824/first-meeting
|
10/10_20/10_20_01/10_18_01.c
|
C
|
unknown
| 380
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
int i, j, k;
scanf("%d %d %d", &i, &j, &k);
if (i >= j)
{
if (k>=i)
{
printf("%d %d %d ", k, i, j);
}
else
{
if (k >= j)
{
printf("%d %d %d ", i, k, j);
}
else
{
printf("%d %d %d ", i, j, k);
}
}
}
else if (j >= k)
{
if (i >= j)
{
printf("%d %d %d ", i, j, k);
}
else
{
if (k >= j)
{
printf("%d %d %d ", j, i, k);
}
else
{
printf("%d %d %d ", j, k, i);
}
}
}
else if (k >=i)
{
if (j >= k)
{
printf("%d %d %d ", j,k,i);
}
else
{
if (k >= j)
{
printf("%d %d %d ", k, j, i);
}
else
{
printf("%d %d %d ", k, i, j);
}
}
}
}
|
2301_77966824/first-meeting
|
10/10_23/10_23_01/10_23_01.c
|
C
|
unknown
| 724
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
/*int sum = 0;
for (int i = 3; i <= 100; i+=3)
{
sum += i;
}
printf("%d", sum);
return 0;*/
/*int i = 1;
do
{
printf("%d ", i);
i++;
}
while (i<=10);*/
/*int i, j = 0;
scanf("%d", &i);
if (i == 0)
{
j++;
}
else
{
while (i)
{
i /= 10;
j++;
}
}
printf("%d",j);*/
int i = 0;
while (i < 10)
{
++i;
if (i == 5)
continue;
printf("%d ", i);
}
}
|
2301_77966824/first-meeting
|
10/10_24/10_24_01/10_24_01.c
|
C
|
unknown
| 472
|
#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
int main()
{
int i, j, k;
scanf("%d %d %d", &i, &j, &k);
if (i >= j){
if (k >= i) {
printf("%d %d %d ", k, i, j);
}
else{
if (k >= j){
printf("%d %d %d ", i, k, j);
}
else{
printf("%d %d %d ", i, j, k);
}
}
}
else if (j >= k){
if (i >= j){
printf("%d %d %d ", i, j, k);
}
else{
if (k >= j){
printf("%d %d %d ", j, i, k);
}
else {
printf("%d %d %d ", j, k, i);
}
}
}
else if (k >= i){
if (j >= k){
printf("%d %d %d ", j, k, i);
}
else{
if (k >= j){
printf("%d %d %d ", k, j, i);
}
else{
printf("%d %d %d ", k, i, j);
}
}
}
}
|
2301_77966824/first-meeting
|
10/10_24/10_24_02/10_24_02.c
|
C
|
unknown
| 682
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
long double num=1.0;
long double temp;
long double sum1 = 0.0;
long double sum2 = 0.0;
for (int i = 1; i <= 100; i+=2)
{
temp = num / i;
sum1 = sum1 + temp;
}
for (int i = 0 ; i <= 100; i += 2)
{
if (i == 0)
{
continue;
}
temp = num / i;
sum2 = sum2 + temp;
}
printf("%llf ", sum1-sum2);
return 0;
}
|
2301_77966824/first-meeting
|
10/10_24/10_24_03/10_24_03.c
|
C
|
unknown
| 395
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int count = 0;
for (int i = 1; i <= 100; i++)
{
if (i % 10 == 9)
{
count++;
}
if ((i / 10) % 10 == 9)
{
count++;
}
}
printf("%d", count);
return 0;
}
|
2301_77966824/first-meeting
|
10/10_24/10_24_04/10_24_04.c
|
C
|
unknown
| 240
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int count = 0;
for (int i = 1000; i <= 2000; i++)
{
if ((i % 100 == 0) && (i % 400 == 0))
{
count++;
}
else if ((i % 100 != 0) && (i % 4 == 0))
{
count++;
}
}
printf("%d",count);
return 0;
}
|
2301_77966824/first-meeting
|
10/10_24/10_24_05/10_24_05.c
|
C
|
unknown
| 281
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int a, b, c, d, e, f, g, h, i, j;
scanf("%d %d %d %d %d %d %d %d %d %d ", &a, &b, &c, &d, &e, &f, &g, &h, &i, &j);
int num1 = a >= b ? a : b;
int num2 = c >= d ? c : d;
int num3 = e >= f ? e : f;
int num4 = g >= h ? g : h;
int num5 = i >= j ? i : j;
int NUM1 = num1 >= num2 ? num1 : num2;
int NUM2 = num3 >= num4 ? num3 : num4;
int MAX = NUM1 >= NUM2 ? NUM1 : NUM2;
int max = MAX >= num5 ? MAX : num5;
printf("%d", max);
return 0;
}
|
2301_77966824/first-meeting
|
10/10_24/10_24_06/10_24_06.c
|
C
|
unknown
| 512
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int main()
{
int arr[10] = { 1,2,3,4,5,6,7,8,9,10 };
int i = 0;
for (i; i < 10; i++)
{
printf("%d\n", arr[i]);
}
printf("\n");
int k = 0;
int num = 0;
for (k; k < 10;k++)
{
scanf("%d", &num);
arr[k ] = num;
}
int j = 0;
while (j < 10)
{
printf("%d\n", arr[j]);
j++;
}
printf("\n");
return 0;
}
|
2301_77966824/first-meeting
|
10/10_26/10_26_04/10_26_04.c
|
C
|
unknown
| 394
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
for (int i = 0; i < 10; i++)
{
for (int j = 1; j <= i; j++)
{
int k = i * j;
printf("%d * %d = %d\t", i, j, k);
}
printf("\n");
}
return 0;
}
|
2301_77966824/first-meeting
|
10/10_27/10_27_02/10_27_02.c
|
C
|
unknown
| 226
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
for (int i = 100; i <= 200; i++)
{
int count = 0;
for (int num = 2; num * num < i; num++)
{
if (i % num == 0)
{
count++;
break;
}
}
if (count == 0)
{
printf("%d\n", i);
}
}
return 0;
}
|
2301_77966824/first-meeting
|
10/10_27/10_27_03/10_27_03.c
|
C
|
unknown
| 290
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int arr[10] = { 0 };
int len = sizeof(arr) / sizeof(int);
int a = 0;
for (int i = 0; i < len; i++)
{
scanf("%d",&a);
arr[i] = a;
}
for (int j = len - 1; j >= 0; j--)
{
printf("%d ", arr[j]);
}
return 0;
}
|
2301_77966824/first-meeting
|
10/10_27/10_27_04,c/10_27_04.c
|
C
|
unknown
| 287
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
#include<stdlib.h>
int main()
{
char arr1[] = {"hello world"};
char arr2[] = {"***********"};
int right = sizeof(arr1) / sizeof(char) - 1;
int left = 0;
while (left <= right)
{
arr2[left] = arr1[left];
arr2[right] = arr1[right];
left++;
right--;
printf("%s\n",arr2);
}
return 0;
}
|
2301_77966824/first-meeting
|
10/10_29/10_29_01/10_29_01.c
|
C
|
unknown
| 354
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int arr1[2][3] = { 0 };
int arr2[3][2] = { 0 };
for (int i = 0; i < 2;i++)
{
for (int j = 0; j < 3; j++)
{
scanf("%d", &arr1[i][j]);
}
}
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 3; j++)
{
printf("%d ", arr1[i][j]);
}
printf("\n");
}
printf("\n");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
arr2[i][j] = arr1[j][i];
//
}
}
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 2; j++)
{
printf("%d ", arr2[i][j]);
}
printf("\n");
}
return 0;
}
|
2301_77966824/first-meeting
|
10/10_29/10_29_02/10_29_02.c
|
C
|
unknown
| 593
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int arr1[] = { 0,1,2,3,4,5,6,7,8,9 };
int len1 = sizeof(arr1) / sizeof(int);
int arr2[] = { 10,11,12,13,14,15,16,17,18,19 };
int len2 = sizeof(arr1) / sizeof(int);
int temp = 0;
for (int i = 0; i < len1; i++)
{
temp = arr1[i];
arr1[i] = arr2[i];
arr2[i] = temp;
}
for (int i = 0; i < len1; i++)
{
printf("arr1 = %d , arr2 = %d\n\n",arr1[i], arr2[i]);
}
return 0;
}
|
2301_77966824/first-meeting
|
10/10_29/10_29_03/10_29_03.c
|
C
|
unknown
| 454
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
double sum = 0;
double arr1[10] = { 0 };
int len = sizeof(arr1) / sizeof(double);
for (int i = 0; i < len; i++)
{
scanf("%lf", &arr1[i]);
sum += arr1[i];
}
double vue = sum / len;
printf("%lf ", vue);
}
|
2301_77966824/first-meeting
|
10/10_29/10_29_04/10_29_04.c
|
C
|
unknown
| 281
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int a;
while (scanf("%d", &a) != EOF)
{
for (int i = 0; i < a; i++)
{
for (int j = 0; j < a; j++)
{
if (i == 0 || j == 0 || j == a-1 || i == a-1)
{
printf("* ");
}
else
{
printf(" ");
}
}
printf("\n");
}
}
return 0;
}
|
2301_77966824/first-meeting
|
10/10_30/10_30_01/10_30_01.c
|
C
|
unknown
| 510
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int num;
while (scanf("%d", &num) != EOF)
{
for (int i = 0; i < num; i++)
{
for (int j = 0; j < num; j++)
{
if (i == j || (i + j) == num - 1)
{
printf("*");
}
else
{
printf(" ");
}
}
printf("\n");
}
}
return 0;
}
|
2301_77966824/first-meeting
|
10/10_30/10_30_02/10_30_02.c
|
C
|
unknown
| 336
|
#define _CRT_SECURE_NO_WARNINGS 1
#include<stdio.h>
int main()
{
int n, m;
while (scanf("%d%d", &n, &m) != EOF)
{
int arr1[n];
int arr2[m];
for (int i = 0; i < n; i++)
{
scanf("%d", &arr1[i]);
}
for (int i = 0; i < m; i++)
{
scanf("%d", &arr2[i]);
}
int i = 0;
int j = 0;
while (i < n && j < m)
{
if (arr1[i] < arr2[j])
{
printf("%d", arr1[i]);
i++;
}
else
{
printf("%d",arr2[j]);
j++;
}
}
while (i < n)
{
printf("%d ", arr1[i]);
i++;
}
while (j < m)
{
printf("%d ", arr2[j]);
j++;
}
}
return 0;
}
|
2301_77966824/first-meeting
|
10/10_30/10_30_03/10_30_03.c
|
C
|
unknown
| 595
|
#include <stdio.h>
int main()
{
printf("Hello World!!!");
return 0;
}
|
2301_77966824/first-meeting
|
10/10_31/10_31_01/10_31_01.c
|
C
|
unknown
| 72
|
int Add(int a,int b)
{
int c=0;
c=a+b;
return c;
}
|
2301_77966824/first-meeting
|
10/10_31/10_31_02/Add.c
|
C
|
unknown
| 55
|
#!/bin/bash
# 定义下载地址和文件名
DOWNLOAD_URL="https://cangjie-lang.cn/v1/files/auth/downLoad?nsId=142267&fileName=Cangjie-0.53.13-linux_x64.tar.gz&objectKey=6719f1eb3af6947e3c6af327"
FILE_NAME="Cangjie-0.53.13-linux_x64.tar.gz"
# 检查 cangjie 工具链是否已安装
echo "确保 cangjie 工具链已安装..."
if ! command -v cjc -v &> /dev/null
then
echo "cangjie工具链 未安装,尝试进行安装..."
# 下载文件
echo "Downloading Cangjie compiler..."
curl -L -o "$FILE_NAME" "$DOWNLOAD_URL"
# 检查下载是否成功
if [ $? -eq 0 ]; then
echo "Download completed successfully."
else
echo "Download failed."
exit 1
fi
# 解压文件
echo "Extracting $FILE_NAME..."
tar -xvf "$FILE_NAME"
# 检查解压是否成功
if [ $? -eq 0 ]; then
echo "Extraction completed successfully."
else
echo "Extraction failed."
exit 1
fi
# 检查 envsetup.sh 是否存在并进行 source
if [[ -f "cangjie/envsetup.sh" ]]; then
echo "envsetup.sh found!"
source cangjie/envsetup.sh
else
echo "envsetup.sh not found!"
exit 1
fi
fi
# 检查 openEuler 防火墙状态
echo "检查 openEuler 防火墙状态..."
if systemctl status firewalld | grep "active (running)" &> /dev/null; then
echo "防火墙已开启,尝试开放 21 端口..."
firewall-cmd --zone=public --add-port=21/tcp --permanent
firewall-cmd --reload
echo "21 端口已开放。"
else
echo "防火墙未开启,无需开放端口。"
fi
# 编译ftp_server
echo "正在编译 ftp_server..."
cjpm build
# 检查编译是否成功
if [ $? -eq 0 ]; then
echo "编译成功."
else
echo "编译失败."
exit 1
fi
# 运行 ftp_server
echo "正在启动 ftp 服务器..."
cjpm run
|
2301_76844282/Cangjie-Examples
|
FTP/run-ftp.sh
|
Shell
|
apache-2.0
| 1,967
|
<!DOCTYPE html>
<html lang="cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div>Hello Cangjie!</div>
<p></p>
<script>
let xhr = new XMLHttpRequest()
xhr.open("POST", "/Hello", true)
xhr.onreadystatechange = () => {
if(xhr.readyState == 4 && xhr.status == 200){
let res = JSON.parse(xhr.responseText)
document.body.innerHTML += `<div>${res.msg}</div>`
}
}
xhr.send(JSON.stringify({
name: "Chen",
age: 999
}))
</script>
</body>
</html>
|
2301_76844282/Cangjie-Examples
|
HTTPServer/index.html
|
HTML
|
apache-2.0
| 687
|
# 基础镜像,可以先执行 docker pull openjdk:17-jdk-slim
FROM openjdk:17-jdk-slim
# 作者
MAINTAINER suke
# 配置
ENV PARAMS=""
# 时区
ENV TZ=PRC
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# 添加应用
ADD target/ai-mcp-knowledge-app.jar /ai-mcp-knowledge-app.jar
ENTRYPOINT ["sh","-c","java -jar $JAVA_OPTS /ai-mcp-knowledge-app.jar $PARAMS"]
|
2301_78711048/ai-mcp-knowledge
|
ai-mcp-knowledge-app/Dockerfile
|
Dockerfile
|
unknown
| 398
|
# 普通镜像构建,随系统版本构建 amd/arm
docker build -t sudonghao/ai-mcp-knowledge-app:2.4 -f ./Dockerfile .
# 兼容 amd、arm 构建镜像
# docker buildx build --load --platform liunx/amd64,linux/arm64 -t fuzhengwei/ai-mcp-knowledge-app:1.0 -f ./Dockerfile . --push
|
2301_78711048/ai-mcp-knowledge
|
ai-mcp-knowledge-app/build.sh
|
Shell
|
unknown
| 282
|
#!/bin/bash
# https://cr.console.aliyun.com/cn-hangzhou/instance/credentials
# Ensure the script exits if any command fails
set -e
# Define variables for the registry and image
ALIYUN_REGISTRY="registry.cn-hangzhou.aliyuncs.com"
NAMESPACE="fuzhengwei"
IMAGE_NAME="ai-mcp-knowledge-app"
IMAGE_TAG="2.4"
# 读取本地配置文件
if [ -f ".local-config" ]; then
source .local-config
else
echo ".local-config 文件不存在,请创建并填写 ALIYUN_USERNAME 和 ALIYUN_PASSWORD"
exit 1
fi
# Login to Aliyun Docker Registry
echo "Logging into Aliyun Docker Registry..."
docker login --username="${ALIYUN_USERNAME}" --password="${ALIYUN_PASSWORD}" $ALIYUN_REGISTRY
# Tag the Docker image
echo "Tagging the Docker image..."
docker tag ${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG} ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}
# Push the Docker image to Aliyun
echo "Pushing the Docker image to Aliyun..."
docker push ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}
echo "Docker image pushed successfully! "
echo "检出地址:docker pull ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}"
echo "标签设置:docker tag ${ALIYUN_REGISTRY}/${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG} ${NAMESPACE}/${IMAGE_NAME}:${IMAGE_TAG}"
# Logout from Aliyun Docker Registry
echo "Logging out from Aliyun Docker Registry..."
docker logout $ALIYUN_REGISTRY
|
2301_78711048/ai-mcp-knowledge
|
ai-mcp-knowledge-app/push.sh
|
Shell
|
unknown
| 1,384
|
package cn.bugstack.knowledge;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
|
2301_78711048/ai-mcp-knowledge
|
ai-mcp-knowledge-app/src/main/java/cn/bugstack/knowledge/Application.java
|
Java
|
unknown
| 314
|
package cn.bugstack.knowledge.config;
import org.springframework.ai.ollama.OllamaEmbeddingModel;
import org.springframework.ai.ollama.api.OllamaApi;
import org.springframework.ai.ollama.api.OllamaOptions;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.pgvector.PgVectorStore;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
@Configuration
public class OllamaConfig {
@Bean("ollamaSimpleVectorStore")
public SimpleVectorStore vectorStore(OllamaApi ollamaApi) {
OllamaEmbeddingModel embeddingModel = OllamaEmbeddingModel
.builder()
.ollamaApi(ollamaApi)
.defaultOptions(OllamaOptions.builder().model("nomic-embed-text").build())
.build();
return SimpleVectorStore.builder(embeddingModel).build();
}
/**
* -- 删除旧的表(如果存在)
* DROP TABLE IF EXISTS public.vector_store_ollama_deepseek;
*
* -- 创建新的表,使用UUID作为主键
* CREATE TABLE public.vector_store_ollama_deepseek (
* id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
* content TEXT NOT NULL,
* metadata JSONB,
* embedding VECTOR(768)
* );
*
* SELECT * FROM vector_store_ollama_deepseek
*/
@Bean("ollamaPgVectorStore")
public PgVectorStore pgVectorStore(OllamaApi ollamaApi, JdbcTemplate jdbcTemplate) {
OllamaEmbeddingModel embeddingModel = OllamaEmbeddingModel
.builder()
.ollamaApi(ollamaApi)
.defaultOptions(OllamaOptions.builder().model("nomic-embed-text").build())
.build();
return PgVectorStore.builder(jdbcTemplate, embeddingModel)
.vectorTableName("vector_store_ollama_deepseek")
.build();
}
}
|
2301_78711048/ai-mcp-knowledge
|
ai-mcp-knowledge-app/src/main/java/cn/bugstack/knowledge/config/OllamaConfig.java
|
Java
|
unknown
| 1,963
|
package cn.bugstack.knowledge.config;
import io.micrometer.observation.ObservationRegistry;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.client.DefaultChatClientBuilder;
import org.springframework.ai.chat.client.advisor.PromptChatMemoryAdvisor;
import org.springframework.ai.chat.client.observation.ChatClientObservationConvention;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.openai.OpenAiChatModel;
import org.springframework.ai.openai.OpenAiChatOptions;
import org.springframework.ai.openai.OpenAiEmbeddingModel;
import org.springframework.ai.openai.api.OpenAiApi;
import org.springframework.ai.tool.ToolCallbackProvider;
import org.springframework.ai.transformer.splitter.TokenTextSplitter;
import org.springframework.ai.vectorstore.SimpleVectorStore;
import org.springframework.ai.vectorstore.pgvector.PgVectorStore;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate;
@Configuration
public class OpenAIConfig {
@Bean
public TokenTextSplitter tokenTextSplitter() {
return new TokenTextSplitter();
}
@Bean
public OpenAiApi openAiApi(@Value("${spring.ai.openai.base-url}") String baseUrl, @Value("${spring.ai.openai.api-key}") String apikey) {
return OpenAiApi.builder()
.baseUrl(baseUrl)
.apiKey(apikey)
.build();
}
@Bean("openAiSimpleVectorStore")
public SimpleVectorStore vectorStore(OpenAiApi openAiApi) {
OpenAiEmbeddingModel embeddingModel = new OpenAiEmbeddingModel(openAiApi);
return SimpleVectorStore.builder(embeddingModel).build();
}
/**
* -- 删除旧的表(如果存在)
* DROP TABLE IF EXISTS public.vector_store_openai;
*
* -- 创建新的表,使用UUID作为主键
* CREATE TABLE public.vector_store_openai (
* id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
* content TEXT NOT NULL,
* metadata JSONB,
* embedding VECTOR(1536)
* );
*
* SELECT * FROM vector_store_openai
*/
@Bean("openAiPgVectorStore")
public PgVectorStore pgVectorStore(OpenAiApi openAiApi, JdbcTemplate jdbcTemplate) {
OpenAiEmbeddingModel embeddingModel = new OpenAiEmbeddingModel(openAiApi);
return PgVectorStore.builder(jdbcTemplate, embeddingModel)
.vectorTableName("vector_store_openai")
.build();
}
@Bean
public ChatClient.Builder chatClientBuilder(OpenAiChatModel openAiChatModel) {
return new DefaultChatClientBuilder(openAiChatModel, ObservationRegistry.NOOP, (ChatClientObservationConvention) null);
}
@Bean
public ChatClient chatClient(OpenAiChatModel openAiChatModel, ToolCallbackProvider tools) {
DefaultChatClientBuilder defaultChatClientBuilder = new DefaultChatClientBuilder(openAiChatModel, ObservationRegistry.NOOP, (ChatClientObservationConvention) null);
return defaultChatClientBuilder
.defaultTools(tools)
.defaultOptions(OpenAiChatOptions.builder()
.model("gpt-4o")
.build())
.build();
}
}
|
2301_78711048/ai-mcp-knowledge
|
ai-mcp-knowledge-app/src/main/java/cn/bugstack/knowledge/config/OpenAIConfig.java
|
Java
|
unknown
| 3,438
|
package cn.bugstack.knowledge.trigger.job;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
@Slf4j
@Service
public class MCPServerCSDNJob {
@Resource
private ChatClient chatClient;
@Scheduled(cron = "0 0 * * * ?")
public void exec() {
// 检查当前时间是否在允许执行的时间范围内(8点到23点之间)
int currentHour = java.time.LocalDateTime.now().getHour();
if (currentHour >= 23 || currentHour < 8) {
log.info("当前时间 {}点 不在任务执行时间范围内,跳过执行", currentHour);
return;
}
try {
String userInput = """
我需要你帮我生成一篇文章,要求如下;
1. 场景为互联网大厂java求职者面试
2. 提问的技术栈如下;
核心语言与平台: Java SE (8/11/17), Jakarta EE (Java EE), JVM
构建工具: Maven, Gradle, Ant
Web框架: Spring Boot, Spring MVC, Spring WebFlux, Jakarta EE, Micronaut, Quarkus, Play Framework, Struts (Legacy)
数据库与ORM: Hibernate, MyBatis, JPA, Spring Data JDBC, HikariCP, C3P0, Flyway, Liquibase
测试框架: JUnit 5, TestNG, Mockito, PowerMock, AssertJ, Selenium, Cucumber
微服务与云原生: Spring Cloud, Netflix OSS (Eureka, Zuul), Consul, gRPC, Apache Thrift, Kubernetes Client, OpenFeign, Resilience4j
安全框架: Spring Security, Apache Shiro, JWT, OAuth2, Keycloak, Bouncy Castle
消息队列: Kafka, RabbitMQ, ActiveMQ, JMS, Apache Pulsar, Redis Pub/Sub
缓存技术: Redis, Ehcache, Caffeine, Hazelcast, Memcached, Spring Cache
日志框架: Log4j2, Logback, SLF4J, Tinylog
监控与运维: Prometheus, Grafana, Micrometer, ELK Stack, New Relic, Jaeger, Zipkin
模板引擎: Thymeleaf, FreeMarker, Velocity, JSP/JSTL
REST与API工具: Swagger/OpenAPI, Spring HATEOAS, Jersey, RESTEasy, Retrofit
序列化: Jackson, Gson, Protobuf, Avro
CI/CD工具: Jenkins, GitLab CI, GitHub Actions, Docker, Kubernetes
大数据处理: Hadoop, Spark, Flink, Cassandra, Elasticsearch
版本控制: Git, SVN
工具库: Apache Commons, Guava, Lombok, MapStruct, JSch, POI
AI:Spring AI, Google A2A, MCP(模型上下文协议), RAG(检索增强生成), Agent(智能代理), 聊天会话内存, 工具执行框架, 提示填充, 向量化, 语义检索, 向量数据库(Milvus/Chroma/Redis), Embedding模型(OpenAI/Ollama), 客户端-服务器架构, 工具调用标准化, 扩展能力, Agentic RAG, 文档加载, 企业文档问答, 复杂工作流, 智能客服系统, AI幻觉(Hallucination), 自然语言语义搜索
其他: JUnit Pioneer, Dubbo, R2DBC, WebSocket
3. 提问的场景方案可包括但不限于;音视频场景,内容社区与UGC,AIGC,游戏与虚拟互动,电商场景,本地生活服务,共享经济,支付与金融服务,互联网医疗,健康管理,医疗供应链,企业协同与SaaS,产业互联网,大数据与AI服务,在线教育,求职招聘,智慧物流,供应链金融,智慧城市,公共服务数字化,物联网应用,Web3.0与区块链,安全与风控,广告与营销,能源与环保。
4. 按照故事场景,以严肃的面试官和搞笑的水货程序员谢飞机进行提问,谢飞机对简单问题可以回答出来,回答好了面试官还会夸赞和引导。复杂问题含糊其辞,回答的不清晰。
5. 每次进行3轮提问,每轮可以有3-5个问题。这些问题要有技术业务场景上的衔接性,循序渐进引导提问。最后是面试官让程序员回家等通知类似的话术。
6. 提问后把问题的答案详细的,写到文章最后,讲述出业务场景和技术点,让小白可以学习下来。
根据以上内容,不要阐述其他信息,请直接提供;文章标题(需要含带技术点)、文章内容、文章标签(多个用英文逗号隔开)、文章简述(100字)
将以上内容发布文章到CSDN
之后进行,微信公众号消息通知,平台:CSDN、主题:为文章标题、描述:为文章简述、跳转地址:为发布文章到CSDN获取 http url 文章地址
""";
log.info("执行结果:{} {}", userInput, chatClient.prompt(userInput).call().content());
} catch (Exception e) {
log.error("定时任务,执行失败", e);
}
}
}
|
2301_78711048/ai-mcp-knowledge
|
ai-mcp-knowledge-trigger/src/main/java/cn/bugstack/knowledge/trigger/job/MCPServerCSDNJob.java
|
Java
|
unknown
| 5,308
|
curl http://117.72.115.188:11434/api/generate \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-r1:1.5b",
"prompt": "1+1",
"stream": false
}'
|
2301_78711048/ai-mcp-knowledge
|
docs/dev-ops/api/curl_local.sh
|
Shell
|
unknown
| 190
|
curl http://58a39caa684c41bf9bed-deepseek-r1-llm-api.gcs-xy1a.jdcloud.com/api/generate \
-H "Content-Type: application/json" \
-d '{
"model": "deepseek-r1:1.5b",
"prompt": "1+1",
"stream": false
}'
|
2301_78711048/ai-mcp-knowledge
|
docs/dev-ops/api/curl_yun.sh
|
Shell
|
unknown
| 231
|
.chat-item {
@apply flex items-center gap-2 p-2 hover:bg-gray-100 rounded cursor-pointer transition-colors;
}
.chat-item.selected {
@apply bg-blue-50; /* 或使用深色背景如bg-gray-200 */
}
.chat-item-content {
@apply flex-1 truncate;
}
.chat-actions {
@apply flex items-center justify-end opacity-0 transition-opacity w-8;
}
.chat-item:hover.chat-actions {
@apply opacity-100;
}
.context-menu {
@apply absolute bg-white border rounded-lg shadow-lg py-1 z-50;
min-width: 120px;
}
.context-menu-item {
@apply px-4 py-2 hover:bg-gray-100 text-sm flex items-center gap-2;
}
.markdown-body {
font-family: -apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,sans-serif,Apple Color Emoji,Segoe UI Emoji;
font-size: 16px;
line-height: 1.5;
word-wrap: break-word;
}
.markdown-body pre {
background-color: #f6f8fa;
border-radius: 6px;
padding: 16px;
overflow-x: auto;
}
.markdown-body code {
background-color: rgba(175,184,193,0.2);
border-radius: 6px;
padding: 0.2em 0.4em;
font-size: 85%;
}
.markdown-body pre code {
background-color: transparent;
padding: 0;
font-size: 100%;
}
.markdown-body h1,.markdown-body h2,.markdown-body h3,
.markdown-body h4,.markdown-body h5,.markdown-body h6 {
margin-top: 24px;
margin-bottom: 16px;
font-weight: 600;
line-height: 1.25;
}
.markdown-body h1 { font-size: 2em; }
.markdown-body h2 { font-size: 1.5em; }
.markdown-body h3 { font-size: 1.25em; }
.markdown-body ul,.markdown-body ol {
padding-left: 2em;
}
.markdown-body ul { list-style-type: disc; }
.markdown-body ol { list-style-type: decimal; }
.markdown-body table {
border-spacing: 0;
border-collapse: collapse;
margin-top: 0;
margin-bottom: 16px;
}
.markdown-body table th,.markdown-body table td {
padding: 6px 13px;
border: 1px solid #d0d7de;
}
.markdown-body table tr:nth-child(2n) {
background-color: #f6f8fa;
}
.chat-actions button {
margin-left: 4px; /* Add some space between buttons */
}
/* 下拉菜单过渡动画 */
#uploadMenu {
transition: all 0.2s ease-out;
transform-origin: top right;
}
#uploadMenu a {
transition: background-color 0.2s ease;
}
|
2301_78711048/ai-mcp-knowledge
|
docs/dev-ops/nginx/html/css/index.css
|
CSS
|
unknown
| 2,351
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>解析仓库</title>
<style>
body {
font-family: 'Microsoft YaHei', '微软雅黑', sans-serif;
background-color: #f0f0f0;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
}
.container {
background-color: white;
padding: 2rem;
border-radius: 10px;
box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
text-align: center;
width: 300px;
}
h1 {
color: #333;
margin-bottom: 1.5rem;
}
.form-group {
margin-bottom: 1rem;
}
input {
width: 100%;
padding: 0.5rem;
border: 1px solid #ccc;
border-radius: 4px;
font-size: 1rem;
box-sizing: border-box;
}
button {
background-color: #1E90FF;
color: white;
border: none;
padding: 0.5rem 1rem;
font-size: 1rem;
border-radius: 4px;
cursor: pointer;
transition: background-color 0.3s;
width: 100%;
}
button:hover {
background-color: #4169E1;
}
#status {
margin-top: 1rem;
font-weight: bold;
}
.overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
z-index: 1000;
justify-content: center;
align-items: center;
}
.loading-spinner {
border: 5px solid #f3f3f3;
border-top: 5px solid #3498db;
border-radius: 50%;
width: 50px;
height: 50px;
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body>
<div class="container">
<h1>上传Git仓库</h1>
<form id="uploadForm">
<div class="form-group">
<input type="text" id="repoUrl" placeholder="Git仓库地址" required>
</div>
<div class="form-group">
<input type="text" id="userName" placeholder="用户名" required>
</div>
<div class="form-group">
<input type="password" id="token" placeholder="密码/Token" required>
</div>
<button type="submit">提交</button>
</form>
<div id="status"></div>
</div>
<div class="overlay" id="loadingOverlay">
<div class="loading-spinner"></div>
</div>
<script>
const loadingOverlay = document.getElementById('loadingOverlay');
document.getElementById('uploadForm').addEventListener('submit', function(e) {
e.preventDefault();
const repoUrl = document.getElementById('repoUrl').value;
const userName = document.getElementById('userName').value;
const token = document.getElementById('token').value;
loadingOverlay.style.display = 'flex';
document.getElementById('status').textContent = '';
fetch('http://localhost:8090/api/v1/rag/analyze_git_repository', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: `repoUrl=${encodeURIComponent(repoUrl)}&userName=${encodeURIComponent(userName)}&token=${encodeURIComponent(token)}`
})
.then(response => response.json())
.then(data => {
loadingOverlay.style.display = 'none';
if (data.code === '0000') {
document.getElementById('status').textContent = '上传成功';
// 成功提示并关闭窗口
setTimeout(() => {
alert('上传成功,窗口即将关闭');
window.close();
}, 500);
} else {
document.getElementById('status').textContent = '上传失败';
}
})
.catch(error => {
loadingOverlay.style.display = 'none';
document.getElementById('status').textContent = '上传仓库时出错';
});
});
</script>
</body>
</html>
|
2301_78711048/ai-mcp-knowledge
|
docs/dev-ops/nginx/html/git.html
|
HTML
|
unknown
| 4,562
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AiRagKnowledge - By 小傅哥</title>
<script src="https://cdn.tailwindcss.com"></script>
<script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/dompurify/dist/purify.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/highlight.js/highlight.min.js"></script>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js/styles/github.min.css">
<link rel="stylesheet" href="css/index.css">
</head>
<body class="h-screen flex flex-col bg-gray-50">
<!-- Top Navigation -->
<nav class="border-b bg-white px-4 py-2 flex items-center gap-2">
<button id="toggleSidebar" class="p-2 hover:bg-gray-100 rounded-lg">
<svg xmlns="http://www.w3.org/2000/svg" class="h-6 w-6 sidebar-icon" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path id="sidebarIconPath" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6h16M4 12h16M4 18h16" />
</svg>
</button>
<button id="newChatBtn" class="flex items-center gap-2 px-3 py-2 hover:bg-gray-100 rounded-lg">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 4v16m8-8H4" />
</svg>
新聊天
</button>
<div class="flex-1 flex items-center gap-4">
<select id="aiModel" class="px-3 py-2 border rounded-lg flex-1 max-w-xs">
<option value="ollama" model="deepseek-r1:1.5b">deepseek-r1:1.5b</option>
<option value="openai" model="gpt-4o">gpt-4o</option>
</select>
<select id="ragSelect" class="px-3 py-2 border rounded-lg flex-1 max-w-xs">
<option value="">选择一个知识库</option>
</select>
</div>
<div class="flex items-center gap-2">
<div class="relative group">
<button id="uploadMenuButton" class="p-2 hover:bg-gray-100 rounded-lg flex items-center gap-1">
🐙上传知识
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clip-rule="evenodd" />
</svg>
</button>
<!-- 下拉菜单 -->
<div class="hidden absolute right-0 mt-2 w-48 bg-white border rounded-md shadow-lg z-50" id="uploadMenu">
<a href="upload.html" target="_blank" class="block px-4 py-2 text-gray-700 hover:bg-gray-100">
📁 上传文件
</a>
<a href="git.html" target="_blank" class="block px-4 py-2 text-gray-700 hover:bg-gray-100">
⎇ 解析仓库(Git)
</a>
</div>
</div>
</div>
</nav>
<div class="flex-1 flex overflow-hidden">
<!-- 侧边栏结构 -->
<aside id="sidebar" class="w-64 bg-white border-r overflow-y-auto transition-all duration-300 ease-in-out">
<div class="p-4">
<h2 class="font-bold mb-2 text-lg">聊天列表</h2>
<ul id="chatList" class="space-y-1">
<!-- 聊天列表项结构修改 -->
</ul>
</div>
</aside>
<!-- Main Content -->
<div class="flex-1 flex flex-col overflow-hidden">
<!-- Chat Area -->
<main class="flex-1 overflow-auto p-4" id="chatArea">
<div id="welcomeMessage" class="flex items-center justify-center h-full">
<div class="bg-white p-6 rounded-lg shadow-md text-center">
<div class="flex items-center gap-2 justify-center text-gray-500 mb-4">
<span class="w-2 h-2 bg-green-500 rounded-full"></span>
Ollama 正在运行 🐏
</div>
<p class="text-gray-600">开始新的对话吧!</p>
</div>
</div>
</main>
<!-- Input Area -->
<div class="p-4">
<div class="max-w-4xl mx-auto">
<div class="border rounded-lg bg-white">
<div class="flex flex-col">
<textarea
id="messageInput"
class="w-full px-3 py-2 min-h-[100px] focus:outline-none resize-none"
placeholder="输入一条消息..."></textarea>
<div class="flex items-center justify-between px-3 py-2 border-t">
<div class="flex items-center gap-2">
<button class="p-2 hover:bg-gray-100 rounded-lg">🌐</button>
</div>
<button
id="submitBtn"
class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 flex items-center gap-2">
提交
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
</svg>
</button>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<script src="js/index.js"></script>
</body>
</html>
|
2301_78711048/ai-mcp-knowledge
|
docs/dev-ops/nginx/html/index.html
|
HTML
|
unknown
| 5,824
|
const chatArea = document.getElementById('chatArea');
const messageInput = document.getElementById('messageInput');
const submitBtn = document.getElementById('submitBtn');
const newChatBtn = document.getElementById('newChatBtn');
const chatList = document.getElementById('chatList');
const welcomeMessage = document.getElementById('welcomeMessage');
const toggleSidebarBtn = document.getElementById('toggleSidebar');
const sidebar = document.getElementById('sidebar');
let currentEventSource = null;
let currentChatId = null;
// 获取知识库列表
document.addEventListener('DOMContentLoaded', function() {
// 获取知识库列表
const loadRagOptions = () => {
const ragSelect = document.getElementById('ragSelect');
fetch('http://localhost:8090/api/v1/rag/query_rag_tag_list')
.then(response => response.json())
.then(data => {
if (data.code === '0000' && data.data) {
// 清空现有选项(保留第一个默认选项)
while (ragSelect.options.length > 1) {
ragSelect.remove(1);
}
// 添加新选项
data.data.forEach(tag => {
const option = new Option(`Rag:${tag}`, tag);
ragSelect.add(option);
});
}
})
.catch(error => {
console.error('获取知识库列表失败:', error);
});
};
// 初始化加载
loadRagOptions();
});
function createNewChat() {
const chatId = Date.now().toString();
currentChatId = chatId;
localStorage.setItem('currentChatId', chatId);
// 修改数据结构为包含name和messages的对象
localStorage.setItem(`chat_${chatId}`, JSON.stringify({
name: '新聊天',
messages: []
}));
updateChatList();
clearChatArea();
}
function deleteChat(chatId) {
if (confirm('确定要删除这个聊天记录吗?')) {
localStorage.removeItem(`chat_${chatId}`); // Remove the chat from localStorage
if (currentChatId === chatId) { // If the current chat is being deleted
createNewChat(); // Create a new chat
}
updateChatList(); // Update the chat list to reflect changes
}
}
function updateChatList() {
chatList.innerHTML = '';
const chats = Object.keys(localStorage)
.filter(key => key.startsWith('chat_'));
const currentChatIndex = chats.findIndex(key => key.split('_')[1] === currentChatId);
if (currentChatIndex!== -1) {
const currentChat = chats[currentChatIndex];
chats.splice(currentChatIndex, 1);
chats.unshift(currentChat);
}
chats.forEach(chatKey => {
let chatData = JSON.parse(localStorage.getItem(chatKey));
const chatId = chatKey.split('_')[1];
// 数据迁移:将旧数组格式转换为新对象格式
if (Array.isArray(chatData)) {
chatData = {
name: `聊天 ${new Date(parseInt(chatId)).toLocaleDateString()}`,
messages: chatData
};
localStorage.setItem(chatKey, JSON.stringify(chatData));
}
const li = document.createElement('li');
li.className = `chat-item flex items-center justify-between p-2 hover:bg-gray-100 rounded-lg cursor-pointer transition-colors ${chatId === currentChatId? 'bg-blue-50' : ''}`;
li.innerHTML = `
<div class="flex-1">
<div class="text-sm font-medium">${chatData.name}</div>
<div class="text-xs text-gray-400">${new Date(parseInt(chatId)).toLocaleDateString('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit' })}</div>
</div>
<div class="chat-actions flex items-center gap-1 opacity-0 transition-opacity duration-200">
<button class="p-1 hover:bg-gray-200 rounded text-gray-500" onclick="renameChat('${chatId}')">重命名</button>
<button class="p-1 hover:bg-red-200 rounded text-red-500" onclick="deleteChat('${chatId}')">删除</button>
</div>
`;
li.addEventListener('click', (e) => {
if (!e.target.closest('.chat-actions')) {
loadChat(chatId);
}
});
li.addEventListener('mouseenter', () => {
li.querySelector('.chat-actions').classList.remove('opacity-0');
});
li.addEventListener('mouseleave', () => {
li.querySelector('.chat-actions').classList.add('opacity-0');
});
chatList.appendChild(li);
});
}
let currentContextMenu = null;
// 优化后的上下文菜单
function showChatContextMenu(event, chatId) {
event.stopPropagation();
closeContextMenu();
const buttonRect = event.target.closest('button').getBoundingClientRect();
const menu = document.createElement('div');
menu.className = 'context-menu';
menu.style.position = 'fixed';
menu.style.left = `${buttonRect.left}px`;
menu.style.top = `${buttonRect.bottom + 4}px`;
menu.innerHTML = `
<div class="context-menu-item" onclick="renameChat('${chatId}')">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/>
</svg>
重命名
</div>
<div class="context-menu-item text-red-500" onclick="deleteChat('${chatId}')">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/>
</svg>
删除
</div>
`;
document.body.appendChild(menu);
currentContextMenu = menu;
// 点击外部关闭菜单
setTimeout(() => {
document.addEventListener('click', closeContextMenu, { once: true });
});
}
function closeContextMenu() {
if (currentContextMenu) {
currentContextMenu.remove();
currentContextMenu = null;
}
}
function renameChat(chatId) {
const chatKey = `chat_${chatId}`;
const chatData = JSON.parse(localStorage.getItem(chatKey));
const currentName = chatData.name || `聊天 ${new Date(parseInt(chatId)).toLocaleString()}`;
const newName = prompt('请输入新的聊天名称', currentName);
if (newName) {
chatData.name = newName;
localStorage.setItem(chatKey, JSON.stringify(chatData));
updateChatList();
}
}
function loadChat(chatId) {
currentChatId = chatId;
localStorage.setItem('currentChatId', chatId);
clearChatArea();
const chatData = JSON.parse(localStorage.getItem(`chat_${chatId}`) || { messages: [] });
chatData.messages.forEach(msg => {
appendMessage(msg.content, msg.isAssistant, false);
});
updateChatList()
}
function clearChatArea() {
chatArea.innerHTML = '';
welcomeMessage.style.display = 'flex';
}
function appendMessage(content, isAssistant = false, saveToStorage = true) {
welcomeMessage.style.display = 'none';
const messageDiv = document.createElement('div');
messageDiv.className = `max-w-4xl mx-auto mb-4 p-4 rounded-lg ${isAssistant ? 'bg-gray-100' : 'bg-white border'} markdown-body relative`;
const renderedContent = DOMPurify.sanitize(marked.parse(content));
messageDiv.innerHTML = renderedContent;
// 添加复制按钮
const copyBtn = document.createElement('button');
copyBtn.className = 'absolute top-2 right-2 p-1 bg-gray-200 rounded-md text-xs';
copyBtn.textContent = '复制';
copyBtn.onclick = () => {
navigator.clipboard.writeText(content).then(() => {
copyBtn.textContent = '已复制';
setTimeout(() => copyBtn.textContent = '复制', 2000);
});
};
messageDiv.appendChild(copyBtn);
chatArea.appendChild(messageDiv);
chatArea.scrollTop = chatArea.scrollHeight;
// 仅在需要时保存到本地存储
if (saveToStorage && currentChatId) {
// 确保读取和保存完整的数据结构
const chatData = JSON.parse(localStorage.getItem(`chat_${currentChatId}`) || '{"name": "新聊天", "messages": []}');
chatData.messages.push({ content, isAssistant });
localStorage.setItem(`chat_${currentChatId}`, JSON.stringify(chatData));
}
}
function startEventStream(message) {
if (currentEventSource) {
currentEventSource.close();
}
// 选项值,
// 组装01;http://localhost:8090/api/v1/ollama/generate_stream?message=Hello&model=deepseek-r1:1.5b
// 组装02;http://localhost:8090/api/v1/openai/generate_stream?message=Hello&model=gpt-4o
const ragTag = document.getElementById('ragSelect').value;
const aiModelSelect = document.getElementById('aiModel');
const aiModelValue = aiModelSelect.value; // 获取选中的 aiModel 的 value
const aiModelModel = aiModelSelect.options[aiModelSelect.selectedIndex].getAttribute('model'); // 获取选中的 aiModel 的 model 属性
let url;
if (ragTag) {
url = `http://localhost:8090/api/v1/${aiModelValue}/generate_stream_rag?message=${encodeURIComponent(message)}&ragTag=${encodeURIComponent(ragTag)}&model=${encodeURIComponent(aiModelModel)}`;
} else {
url = `http://localhost:8090/api/v1/${aiModelValue}/generate_stream?message=${encodeURIComponent(message)}&model=${encodeURIComponent(aiModelModel)}`;
}
currentEventSource = new EventSource(url);
let accumulatedContent = '';
let tempMessageDiv = null;
currentEventSource.onmessage = function(event) {
try {
const data = JSON.parse(event.data);
if (data.result?.output?.content) {
const newContent = data.result.output.content;
accumulatedContent += newContent;
// 首次创建临时消息容器
if (!tempMessageDiv) {
tempMessageDiv = document.createElement('div');
tempMessageDiv.className = 'max-w-4xl mx-auto mb-4 p-4 rounded-lg bg-gray-100 markdown-body relative';
chatArea.appendChild(tempMessageDiv);
welcomeMessage.style.display = 'none';
}
// 直接更新文本内容(先不解析Markdown)
tempMessageDiv.textContent = accumulatedContent;
chatArea.scrollTop = chatArea.scrollHeight;
}
if (data.result?.output?.properties?.finishReason === 'STOP') {
currentEventSource.close();
// 流式传输完成后进行最终渲染
const finalContent = accumulatedContent;
tempMessageDiv.innerHTML = DOMPurify.sanitize(marked.parse(finalContent));
// 添加复制按钮
const copyBtn = document.createElement('button');
copyBtn.className = 'absolute top-2 right-2 p-1 bg-gray-200 rounded-md text-xs';
copyBtn.textContent = '复制';
copyBtn.onclick = () => {
navigator.clipboard.writeText(finalContent).then(() => {
copyBtn.textContent = '已复制';
setTimeout(() => copyBtn.textContent = '复制', 2000);
});
};
tempMessageDiv.appendChild(copyBtn);
// 保存到本地存储
if (currentChatId) {
// 正确的数据结构应该是对象包含messages数组
const chatData = JSON.parse(localStorage.getItem(`chat_${currentChatId}`) || '{"name": "新聊天", "messages": []}');
chatData.messages.push({ content: finalContent, isAssistant: true });
localStorage.setItem(`chat_${currentChatId}`, JSON.stringify(chatData));
}
}
} catch (e) {
console.error('Error parsing event data:', e);
}
};
currentEventSource.onerror = function(error) {
console.error('EventSource error:', error);
currentEventSource.close();
};
}
submitBtn.addEventListener('click', () => {
const message = messageInput.value.trim();
if (!message) return;
if (!currentChatId) {
createNewChat();
}
appendMessage(message, false);
messageInput.value = '';
startEventStream(message);
});
messageInput.addEventListener('keypress', (e) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
submitBtn.click();
}
});
newChatBtn.addEventListener('click', createNewChat);
toggleSidebarBtn.addEventListener('click', () => {
sidebar.classList.toggle('-translate-x-full');
updateSidebarIcon();
});
function updateSidebarIcon() {
const iconPath = document.getElementById('sidebarIconPath');
if (sidebar.classList.contains('-translate-x-full')) {
iconPath.setAttribute('d', 'M4 6h16M4 12h4m12 0h-4M4 18h16');
} else {
iconPath.setAttribute('d', 'M4 6h16M4 12h16M4 18h16');
}
}
// Initialize
updateChatList();
const savedChatId = localStorage.getItem('currentChatId');
if (savedChatId) {
loadChat(savedChatId);
}
// Handle window resize for responsive design
window.addEventListener('resize', () => {
if (window.innerWidth > 768) {
sidebar.classList.remove('-translate-x-full');
} else {
sidebar.classList.add('-translate-x-full');
}
});
// Initial check for mobile devices
if (window.innerWidth <= 768) {
sidebar.classList.add('-translate-x-full');
}
updateSidebarIcon();
// 上传知识下拉菜单控制
const uploadMenuButton = document.getElementById('uploadMenuButton');
const uploadMenu = document.getElementById('uploadMenu');
// 切换菜单显示
uploadMenuButton.addEventListener('click', (e) => {
e.stopPropagation();
uploadMenu.classList.toggle('hidden');
});
// 点击外部区域关闭菜单
document.addEventListener('click', (e) => {
if (!uploadMenu.contains(e.target) && e.target !== uploadMenuButton) {
uploadMenu.classList.add('hidden');
}
});
// 菜单项点击后关闭菜单
document.querySelectorAll('#uploadMenu a').forEach(item => {
item.addEventListener('click', () => {
uploadMenu.classList.add('hidden');
});
});
|
2301_78711048/ai-mcp-knowledge
|
docs/dev-ops/nginx/html/js/index.js
|
JavaScript
|
unknown
| 14,751
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>文件上传</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script src="https://cdn.tailwindcss.com"></script>
<style>
/* 加载动画 */
.loader {
animation: spin 1s linear infinite;
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
</style>
</head>
<body class="flex justify-center items-center min-h-screen bg-gray-100">
<!-- 上传文件模态框 -->
<div class="bg-white p-6 rounded-lg shadow-lg w-96 relative">
<!-- 加载遮罩层 -->
<div id="loadingOverlay" class="hidden absolute inset-0 bg-white bg-opacity-90 flex flex-col items-center justify-center rounded-lg">
<div class="loader mb-4">
<svg class="h-8 w-8 text-blue-600" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M12 2V6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<path d="M12 18V22" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<path d="M4.93 4.93L7.76 7.76" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<path d="M16.24 16.24L19.07 19.07" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<path d="M2 12H6" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<path d="M18 12H22" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<path d="M4.93 19.07L7.76 16.24" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
<path d="M16.24 7.76L19.07 4.93" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
</svg>
</div>
<p class="text-gray-600">文件上传中,请稍候...</p>
</div>
<h2 class="text-xl font-semibold text-center mb-4">添加知识</h2>
<form id="uploadForm" enctype="multipart/form-data">
<!-- 知识标题输入 -->
<div class="mb-4">
<label for="title" class="block text-sm font-medium text-gray-700">知识标题</label>
<input type="text" id="title" name="title" class="mt-1 block w-full p-2 border border-gray-300 rounded-md" placeholder="输入知识标题" required />
</div>
<!-- 上传文件区域 -->
<div class="mb-4">
<label for="file" class="block text-sm font-medium text-gray-700">上传文件</label>
<div class="mt-2 border-dashed border-2 border-gray-300 p-4 text-center text-gray-500">
<input type="file" id="file" name="file" accept=".pdf,.csv,.txt,.md,.sql,.java" class="hidden" multiple />
<label for="file" class="cursor-pointer">
<div>将文件拖到此处或点击上传</div>
<div class="mt-2 text-sm text-gray-400">支持的文件类型:.pdf, .csv, .txt, .md, .sql, .java</div>
</label>
</div>
</div>
<!-- 待上传文件列表 -->
<div class="mb-4" id="fileList">
<ul class="list-disc pl-5 text-gray-700"></ul>
</div>
<!-- 提交按钮 -->
<div class="flex justify-center">
<button type="submit" class="bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700">
提交
</button>
</div>
</form>
</div>
<script>
const fileListElement = document.querySelector('#fileList ul');
// 文件选择变更处理
document.getElementById('file').addEventListener('change', function (e) {
const files = Array.from(e.target.files);
fileListElement.innerHTML = ''; // 清空列表
files.forEach((file, index) => {
const listItem = document.createElement('li');
listItem.className = 'flex justify-between items-center';
listItem.innerHTML = `
<span>${file.name}</span>
<button type="button" class="text-red-500 hover:text-red-700" onclick="removeFile(${index})">删除</button>
`;
fileListElement.appendChild(listItem);
});
});
// 移除文件
function removeFile(index) {
const input = document.getElementById('file');
let files = Array.from(input.files);
files.splice(index, 1);
// 创建一个新的DataTransfer对象
const dataTransfer = new DataTransfer();
files.forEach(file => dataTransfer.items.add(file));
// 更新文件输入对象的文件列表
input.files = dataTransfer.files;
// 更新文件列表UI
const fileListItems = fileListElement.children;
fileListItems[index].remove();
}
// 提交事件处理
document.getElementById('uploadForm').addEventListener('submit', function (e) {
e.preventDefault();
const loadingOverlay = document.getElementById('loadingOverlay');
const input = document.getElementById('file');
const files = Array.from(input.files);
if (files.length === 0) {
alert('请先选择一个文件');
return;
}
// 显示加载状态
loadingOverlay.classList.remove('hidden');
const formData = new FormData();
formData.append('ragTag', document.getElementById('title').value);
files.forEach(file => formData.append('file', file));
axios.post('http://localhost:8090/api/v1/rag/file/upload', formData)
.then(response => {
if (response.data.code === '0000') {
// 成功提示并关闭窗口
setTimeout(() => {
alert('上传成功,窗口即将关闭');
window.close();
}, 500);
} else {
throw new Error(response.data.info || '上传失败');
}
})
.catch(error => {
alert(error.message);
})
.finally(() => {
// 隐藏加载状态
loadingOverlay.classList.add('hidden');
// 清空表单(无论成功与否)
input.value = '';
document.getElementById('title').value = '';
fileListElement.innerHTML = '';
});
});
</script>
</body>
</html>
|
2301_78711048/ai-mcp-knowledge
|
docs/dev-ops/nginx/html/upload.html
|
HTML
|
unknown
| 6,434
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chat</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 h-screen">
<div class="container mx-auto max-w-3xl h-screen flex flex-col">
<!-- 消息容器 -->
<div id="messageContainer" class="flex-1 overflow-y-auto p-4 space-y-4 bg-white rounded-lg shadow-lg">
<!-- 消息历史将在此动态生成 -->
</div>
<!-- 输入区域 -->
<div class="p-4 bg-white rounded-lg shadow-lg mt-4">
<div class="flex space-x-2">
<input
type="text"
id="messageInput"
placeholder="输入消息..."
class="flex-1 p-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500"
onkeypress="handleKeyPress(event)"
>
<button
onclick="sendMessage()"
class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors"
>
发送
</button>
</div>
</div>
</div>
<script>
// 添加消息到容器
function addMessage(content, isUser = false) {
const container = document.getElementById('messageContainer');
const messageDiv = document.createElement('div');
messageDiv.className = `flex ${isUser ? 'justify-end' : 'justify-start'}`;
messageDiv.innerHTML = `
<div class="max-w-[80%] p-3 rounded-lg ${
isUser ? 'bg-blue-500 text-white' : 'bg-gray-200 text-gray-800'
}">
${content}
</div>
`;
container.appendChild(messageDiv);
container.scrollTop = container.scrollHeight; // 滚动到底部
}
// 发送消息
async function sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value.trim();
if (!message) return;
// 清空输入框
input.value = '';
// 添加用户消息
addMessage(message, true);
// 添加初始AI消息占位
addMessage('<span class="animate-pulse">▍</span>');
// 构建API URL
const apiUrl = `http://localhost:8090/api/v1/ollama/generate_stream?model=deepseek-r1:1.5b&message=${encodeURIComponent(message)}`;
// 使用EventSource接收流式响应
const eventSource = new EventSource(apiUrl);
let buffer = '';
eventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
const content = data.result?.output?.content || '';
const finishReason = data.result?.metadata?.finishReason;
if (content) {
buffer += content;
updateLastMessage(buffer + '<span class="animate-pulse">▍</span>');
}
if (finishReason === 'STOP') {
eventSource.close();
updateLastMessage(buffer); // 移除加载动画
}
} catch (error) {
console.error('解析错误:', error);
}
};
eventSource.onerror = (error) => {
console.error('EventSource错误:', error);
eventSource.close();
};
}
// 更新最后一条消息
function updateLastMessage(content) {
const container = document.getElementById('messageContainer');
const lastMessage = container.lastChild.querySelector('div');
lastMessage.innerHTML = content;
container.scrollTop = container.scrollHeight;
}
// 回车发送
function handleKeyPress(event) {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
sendMessage();
}
}
</script>
</body>
</html>
|
2301_78711048/ai-mcp-knowledge
|
docs/dev-ops/nginx/html/第4节:ai-case-04.html
|
HTML
|
unknown
| 4,288
|
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chat Interface</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-50">
<div class="flex h-screen">
<!-- Sidebar -->
<div id="sidebar" class="w-64 bg-white border-r border-gray-200 flex flex-col">
<div class="p-4">
<button id="newChatBtn" class="w-full flex items-center gap-2 px-4 py-2 bg-gray-100 hover:bg-gray-200 rounded-lg transition-colors">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M10 3a1 1 0 011 1v5h5a1 1 0 110 2h-5v5a1 1 0 11-2 0v-5H4a1 1 0 110-2h5V4a1 1 0 011-1z" clip-rule="evenodd" />
</svg>
新聊天
</button>
</div>
<div id="chatList" class="flex-1 overflow-y-auto p-2 space-y-2"></div>
</div>
<!-- Main Content -->
<div class="flex-1 flex flex-col">
<!-- Top Bar -->
<div class="bg-white border-b border-gray-200 p-4 flex items-center gap-4">
<select id="modelSelect" class="px-4 py-2 border rounded-lg flex-1 max-w-xs">
<option value="deepseek-r1:1.5b">deepseek-r1</option>
</select>
<select id="promptSelect" class="px-4 py-2 border rounded-lg flex-1 max-w-xs text-gray-400">
<option>选择一个提示词</option>
</select>
</div>
<!-- Chat Area -->
<div id="chatArea" class="flex-1 overflow-y-auto p-4 space-y-4"></div>
<!-- Input Area -->
<div class="bg-white border-t border-gray-200 p-4">
<div class="max-w-4xl mx-auto flex flex-col gap-4">
<textarea id="messageInput" rows="3" class="w-full p-3 rounded-lg border border-gray-200 focus:outline-none focus:ring-2 focus:ring-blue-500" placeholder="输入一条消息..."></textarea>
<div class="flex justify-between items-center">
<div class="flex items-center gap-2">
<button class="p-2 hover:bg-gray-100 rounded-lg">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M4 5a2 2 0 00-2 2v8a2 2 0 002 2h12a2 2 0 002-2V7a2 2 0 00-2-2h-1.586a1 1 0 01-.707-.293l-1.121-1.121A2 2 0 0011.172 3H8.828a2 2 0 00-1.414.586L6.293 4.707A1 1 0 015.586 5H4zm6 9a3 3 0 100-6 3 3 0 000 6z" clip-rule="evenodd" />
</svg>
</button>
<button class="p-2 hover:bg-gray-100 rounded-lg">
<svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M7 4a3 3 0 016 0v4a3 3 0 11-6 0V4zm4 10.93A7.001 7.001 0 0017 8a1 1 0 10-2 0A5 5 0 015 8a1 1 0 00-2 0 7.001 7.001 0 006 6.93V17H6a1 1 0 100 2h8a1 1 0 100-2h-3v-2.07z" clip-rule="evenodd" />
</svg>
</button>
</div>
<button id="sendBtn" class="px-4 py-2 bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors">
发送
</button>
</div>
</div>
</div>
</div>
</div>
<script>
// Chat management
let chats = [];
let currentChatId = null;
// Initialize chat interface
document.addEventListener('DOMContentLoaded', () => {
// New chat button handler
document.getElementById('newChatBtn').addEventListener('click', createNewChat);
// Send message button handler
document.getElementById('sendBtn').addEventListener('click', sendMessage);
// Create initial chat
createNewChat();
});
function createNewChat() {
const chatId = Date.now().toString();
const chat = {
id: chatId,
name: `新对话 ${chats.length + 1}`,
messages: []
};
chats.push(chat);
currentChatId = chatId;
// Add to sidebar
const chatList = document.getElementById('chatList');
const chatElement = createChatListItem(chat);
chatList.appendChild(chatElement);
// Clear chat area
document.getElementById('chatArea').innerHTML = '';
document.getElementById('messageInput').value = '';
}
function createChatListItem(chat) {
const div = document.createElement('div');
div.className = 'flex items-center justify-between p-2 hover:bg-gray-100 rounded-lg cursor-pointer group';
div.innerHTML = `
<span class="flex-1">${chat.name}</span>
<div class="hidden group-hover:flex items-center gap-2">
<button onclick="renameChatPrompt('${chat.id}')" class="p-1 hover:bg-gray-200 rounded">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
<path d="M13.586 3.586a2 2 0 112.828 2.828l-.793.793-2.828-2.828.793-.793zM11.379 5.793L3 14.172V17h2.828l8.38-8.379-2.83-2.828z" />
</svg>
</button>
<button onclick="deleteChat('${chat.id}')" class="p-1 hover:bg-gray-200 rounded">
<svg xmlns="http://www.w3.org/2000/svg" class="h-4 w-4" viewBox="0 0 20 20" fill="currentColor">
<path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
</svg>
</button>
</div>
`;
div.addEventListener('click', (e) => {
if (!e.target.closest('button')) {
selectChat(chat.id);
}
});
return div;
}
function selectChat(chatId) {
currentChatId = chatId;
const chat = chats.find(c => c.id === chatId);
// Update chat area
const chatArea = document.getElementById('chatArea');
chatArea.innerHTML = '';
chat.messages.forEach(msg => {
appendMessage(msg.role, msg.content);
});
}
function renameChatPrompt(chatId) {
const chat = chats.find(c => c.id === chatId);
const newName = prompt('请输入新的对话名称:', chat.name);
if (newName) {
chat.name = newName;
updateChatList();
}
}
function deleteChat(chatId) {
if (confirm('确定要删除这个对话吗?')) {
chats = chats.filter(c => c.id !== chatId);
updateChatList();
if (currentChatId === chatId) {
if (chats.length > 0) {
selectChat(chats[0].id);
} else {
createNewChat();
}
}
}
}
function updateChatList() {
const chatList = document.getElementById('chatList');
chatList.innerHTML = '';
chats.forEach(chat => {
chatList.appendChild(createChatListItem(chat));
});
}
function appendMessage(role, content) {
const chatArea = document.getElementById('chatArea');
const messageDiv = document.createElement('div');
messageDiv.className = `flex ${role === 'user' ? 'justify-end' : 'justify-start'}`;
const bubble = document.createElement('div');
bubble.className = `max-w-[80%] p-3 rounded-lg ${
role === 'user'
? 'bg-blue-500 text-white'
: 'bg-gray-100 text-gray-800'
}`;
bubble.textContent = content;
messageDiv.appendChild(bubble);
chatArea.appendChild(messageDiv);
chatArea.scrollTop = chatArea.scrollHeight;
}
async function sendMessage() {
const input = document.getElementById('messageInput');
const message = input.value.trim();
if (!message) return;
// Clear input
input.value = '';
// Add user message
appendMessage('user', message);
// Get current chat
const chat = chats.find(c => c.id === currentChatId);
chat.messages.push({ role: 'user', content: message });
// Create API URL with parameters
const model = document.getElementById('modelSelect').value;
const apiUrl = `http://localhost:8090/api/v1/ollama/generate_stream?model=${encodeURIComponent(model)}&message=${encodeURIComponent(message)}`;
try {
// Create temporary div for assistant's response
const assistantMessage = document.createElement('div');
assistantMessage.className = 'flex justify-start';
const bubble = document.createElement('div');
bubble.className = 'max-w-[80%] p-3 rounded-lg bg-gray-100 text-gray-800';
assistantMessage.appendChild(bubble);
document.getElementById('chatArea').appendChild(assistantMessage);
// Set up EventSource
const eventSource = new EventSource(apiUrl);
let fullResponse = '';
eventSource.onmessage = (event) => {
try {
const data = JSON.parse(event.data);
const content = data.result.output.content;
const finishReason = data.result.metadata.finishReason;
if (content) {
fullResponse += content;
bubble.textContent = fullResponse;
document.getElementById('chatArea').scrollTop = document.getElementById('chatArea').scrollHeight;
}
if (finishReason === 'STOP') {
eventSource.close();
chat.messages.push({ role: 'assistant', content: fullResponse });
}
} catch (error) {
console.error('Error parsing message:', error);
}
};
eventSource.onerror = (error) => {
console.error('EventSource failed:', error);
eventSource.close();
};
} catch (error) {
console.error('Error sending message:', error);
}
}
</script>
</body>
</html>
|
2301_78711048/ai-mcp-knowledge
|
docs/dev-ops/nginx/html/第7节:ai-case-01.html
|
HTML
|
unknown
| 11,283
|
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>知识库上传</title>
<script src="https://cdn.tailwindcss.com"></script>
</head>
<body class="bg-gray-100 min-h-screen p-8">
<div class="max-w-2xl mx-auto bg-white rounded-xl shadow-md p-6">
<h1 class="text-2xl font-bold text-gray-800 mb-6">知识库上传</h1>
<!-- 错误提示 -->
<div id="error" class="hidden mb-4 p-3 bg-red-100 text-red-700 rounded-lg"></div>
<!-- 上传表单 -->
<form id="uploadForm" class="space-y-4">
<!-- 知识库名称 -->
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">知识库名称</label>
<input
type="text"
id="ragTag"
class="w-full px-4 py-2 border rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
placeholder="请输入知识库名称"
required>
</div>
<!-- 文件上传区域 -->
<div>
<label class="block text-sm font-medium text-gray-700 mb-1">选择文件</label>
<div class="flex items-center justify-center w-full">
<label class="flex flex-col w-full border-2 border-dashed rounded-lg hover:border-gray-400 transition-colors h-32">
<div class="flex flex-col items-center justify-center pt-5 h-full">
<svg class="w-8 h-8 text-gray-400 mb-2" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"/>
</svg>
<span class="text-sm text-gray-500">点击选择文件或拖拽到此区域</span>
<span class="text-xs text-gray-400">支持格式:md, txt, sql</span>
</div>
<input
type="file"
id="fileInput"
class="hidden"
multiple
accept=".md,.txt,.sql">
</label>
</div>
<!-- 文件列表 -->
<div id="fileList" class="mt-2 space-y-1"></div>
</div>
<!-- 上传按钮 -->
<button
type="submit"
class="w-full bg-blue-600 text-white py-2 px-4 rounded-lg hover:bg-blue-700 transition-colors flex items-center justify-center">
<svg id="spinner" class="hidden w-4 h-4 mr-2 animate-spin" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4" fill="none"/>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"/>
</svg>
开始上传
</button>
</form>
</div>
<script>
const form = document.getElementById('uploadForm');
const fileInput = document.getElementById('fileInput');
const fileList = document.getElementById('fileList');
const errorDiv = document.getElementById('error');
const spinner = document.getElementById('spinner');
// 显示文件列表
fileInput.addEventListener('change', () => {
fileList.innerHTML = '';
Array.from(fileInput.files).forEach(file => {
const div = document.createElement('div');
div.className = 'text-sm text-gray-600 flex justify-between items-center';
div.innerHTML = `
<span>${file.name}</span>
<span class="text-gray-400">${(file.size / 1024).toFixed(2)}KB</span>
`;
fileList.appendChild(div);
});
});
// 提交表单
form.addEventListener('submit', async (e) => {
e.preventDefault();
const ragTag = document.getElementById('ragTag').value.trim();
const files = fileInput.files;
// 验证输入
if (!ragTag) {
showError('请输入知识库名称');
return;
}
if (files.length === 0) {
showError('请选择至少一个文件');
return;
}
// 验证文件类型
const allowedTypes = ['text/markdown', 'text/plain', 'application/sql'];
const invalidFiles = Array.from(files).filter(file =>
!allowedTypes.includes(file.type)
);
if (invalidFiles.length > 0) {
showError(`无效文件类型:${invalidFiles.map(f => f.name).join(', ')}`);
return;
}
// 开始上传
try {
toggleLoading(true);
const formData = new FormData();
formData.append('ragTag', ragTag);
Array.from(files).forEach(file => {
formData.append('file', file);
});
const response = await fetch('http://localhost:8090/api/v1/rag/file/upload', {
method: 'POST',
body: formData
});
const result = await response.json();
if (result.code === '0000') {
alert('上传成功!');
form.reset();
fileList.innerHTML = '';
} else {
showError(result.info || '上传失败');
}
} catch (err) {
showError('网络错误,请稍后重试');
} finally {
toggleLoading(false);
}
});
function showError(message) {
errorDiv.textContent = message;
errorDiv.classList.remove('hidden');
setTimeout(() => errorDiv.classList.add('hidden'), 3000);
}
function toggleLoading(isLoading) {
spinner.classList.toggle('hidden', !isLoading);
form.querySelector('button').disabled = isLoading;
}
</script>
</body>
</html>
|
2301_78711048/ai-mcp-knowledge
|
docs/dev-ops/nginx/html/第7节:ai-case-02.html
|
HTML
|
unknown
| 6,417
|
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>AI Chat Interface</title>
<script src="https://cdn.tailwindcss.com"></script>
<script>
// Simple utility to handle sending messages and receiving data from the server.
async function sendMessage(chatId, message) {
const chatBox = document.getElementById(chatId);
const inputField = document.getElementById("user-input");
// Append user's message to the chat
chatBox.innerHTML += `<div class="p-2 mb-2 bg-gray-200 rounded-md text-left">${message}</div>`;
inputField.value = ''; // Clear input field
const apiUrl = `/api/v1/ollama/generate_stream?model=deepseek-r1:1.5b&message=${encodeURIComponent(message)}`;
const eventSource = new EventSource(apiUrl);
eventSource.onmessage = function (event) {
const response = JSON.parse(event.data);
const content = response[0]?.result?.output?.content;
const finishReason = response[0]?.result?.metadata?.finishReason;
if (content) {
chatBox.innerHTML += `<div class="p-2 mb-2 bg-gray-100 rounded-md text-right">${content}</div>`;
}
if (finishReason === "STOP") {
eventSource.close();
}
};
}
// Create new chat
function createNewChat() {
const chatList = document.getElementById('chat-list');
const chatId = 'chat-' + Date.now();
const newChat = document.createElement('div');
newChat.className = 'chat-item p-2 hover:bg-gray-200 cursor-pointer';
newChat.innerHTML = `<span class="text-sm">Chat ${chatList.children.length + 1}</span>`;
newChat.setAttribute('data-chat-id', chatId);
newChat.onclick = function () { selectChat(chatId); };
chatList.appendChild(newChat);
}
// Select chat
function selectChat(chatId) {
const chats = document.querySelectorAll('.chat-item');
chats.forEach(chat => chat.classList.remove('bg-gray-300'));
const selectedChat = document.querySelector(`[data-chat-id="${chatId}"]`);
selectedChat.classList.add('bg-gray-300');
// Display the chat box
const chatBox = document.getElementById('chat-box');
chatBox.innerHTML = `<div id="${chatId}" class="p-4 overflow-y-auto h-96 bg-gray-50 rounded-md"></div>`;
}
// Handle send button click or Enter key press
function handleSend() {
const message = document.getElementById("user-input").value.trim();
if (message) {
const activeChat = document.querySelector('.chat-item.bg-gray-300');
if (activeChat) {
const chatId = activeChat.getAttribute('data-chat-id');
sendMessage(chatId, message);
}
}
}
// Handle Enter key press for sending a message
document.getElementById('user-input').addEventListener('keydown', function (e) {
if (e.key === 'Enter') {
e.preventDefault();
handleSend();
}
});
</script>
</head>
<body class="bg-gray-100 h-screen flex flex-col">
<!-- Top Bar -->
<div class="flex items-center justify-between bg-white p-4 shadow-md">
<div class="flex items-center space-x-2">
<button onclick="createNewChat()" class="px-4 py-2 bg-blue-500 text-white rounded-md">新聊天</button>
</div>
<div class="flex space-x-4">
<select class="p-2 border rounded-md">
<option>deepseek-r1</option>
</select>
<span class="text-green-500">Ollama正在运行 🦙</span>
</div>
</div>
<div class="flex flex-1">
<!-- Left Sidebar (Chat List) -->
<div class="w-1/4 p-4 overflow-y-auto bg-white shadow-md">
<div id="chat-list">
<!-- Chat items will appear here -->
</div>
</div>
<!-- Chat Area -->
<div class="flex-1 p-6 flex flex-col space-y-4">
<div id="chat-box" class="bg-gray-100 p-4 rounded-md h-full overflow-y-auto">
<!-- Messages will appear here -->
</div>
<!-- Message Input Section -->
<div class="flex space-x-2 items-center">
<input id="user-input" type="text" placeholder="输入一条消息..." class="flex-1 p-2 border rounded-md focus:outline-none">
<button onclick="handleSend()" class="px-4 py-2 bg-blue-500 text-white rounded-md">提交</button>
</div>
</div>
</div>
</body>
</html>
|
2301_78711048/ai-mcp-knowledge
|
docs/dev-ops/nginx/html/第7节:ai-case-03.html
|
HTML
|
unknown
| 4,815
|
cmake_minimum_required(VERSION 3.14)
project(ukui-mstm)
set(VERSION_MAJOR 1)
set(VERSION_MINOR 0)
set(VERSION_MICRO 0)
set(UKUI_STMS_VERSION ${VERSION_MAJOR}.${VERSION_MINOR}.${VERSION_MICRO})
set(CMAKE_INCLUDE_CURRENT_DIR ON)
set(CMAKE_AUTOMOC ON)
set(CMAKE_AUTORCC ON)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
find_package(QT NAMES Qt6 Qt5 COMPONENTS Core Gui Widgets Quick REQUIRED)
find_package(Qt${QT_VERSION_MAJOR} COMPONENTS Core Gui Widgets Quick REQUIRED)
find_package(PkgConfig REQUIRED)
set(PROJECT_SOURCES
plugin/mstm.cpp
plugin/mstm.h
plugin/ukui-mstm-plugin.cpp
plugin/ukui-mstm-plugin.h
)
qt5_add_resources(QRC_FILES plugin/res.qrc)
if(${QT_VERSION_MAJOR} GREATER_EQUAL 6)
add_library(${PROJECT_NAME} SHARED MANUAL_FINALIZATION ${PROJECT_SOURCES} ${QRC_FILES})
else()
add_library(${PROJECT_NAME} SHARED ${PROJECT_SOURCES} ${QRC_FILES})
endif()
target_compile_definitions(${PROJECT_NAME}
PRIVATE $<$<OR:$<CONFIG:Debug>>:QT_QML_DEBUG>
)
target_link_libraries(${PROJECT_NAME}
PRIVATE
Qt${QT_VERSION_MAJOR}::Core
Qt${QT_VERSION_MAJOR}::Quick
Qt${QT_MAJOR_VERSION}::Gui
Qt${QT_VERSION_MAJOR}::Widgets
)
install(DIRECTORY "widget/" DESTINATION /usr/share/ukui/widgets/org.ukui.mstm)
install(FILES "plugin/qmldir" DESTINATION "/usr/lib/${CMAKE_LIBRARY_ARCHITECTURE}/qt5/qml/org/ukui/mstm")
install(TARGETS ${PROJECT_NAME} LIBRARY DESTINATION "/usr/lib/${CMAKE_LIBRARY_ARCHITECTURE}/qt5/qml/org/ukui/mstm")
|
2301_79280419/UKUI-quick
|
CMakeLists.txt
|
CMake
|
unknown
| 1,505
|
#include "mstm.h"
STMS::STMS(QObject *parent) : QObject(parent)
{
}
|
2301_79280419/UKUI-quick
|
plugin/mstm.cpp
|
C++
|
unknown
| 70
|
#ifndef MTS_H
#define MTS_H
#include <QObject>
#include <QTimer>
#include <QString>
class STMS : public QObject
{
Q_OBJECT
public:
explicit STMS(QObject *parent = nullptr);
};
#endif // MTS_H
|
2301_79280419/UKUI-quick
|
plugin/mstm.h
|
C++
|
unknown
| 205
|
#include "ukui-mstm-plugin.h"
#include "mstm.h"
#include <QQmlEngine>
void UkuiStmsPlugin::registerTypes(const char* uri)
{
Q_ASSERT(QString(uri) == QLatin1String("org.ukui.mstm"));
qmlRegisterModule(uri, 1, 0);
qmlRegisterType<STMS>(uri, 1, 0, "MSTM");
Q_INIT_RESOURCE(res);
}
|
2301_79280419/UKUI-quick
|
plugin/ukui-mstm-plugin.cpp
|
C++
|
unknown
| 295
|
#ifndef UKUI_MTS_PLUGIN_H
#define UKUI_MTS_PLUGIN_H
#include <QQmlExtensionPlugin>
class UkuiStmsPlugin : public QQmlExtensionPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID QQmlExtensionInterface_iid)
public:
void registerTypes(const char *uri) override;
};
#endif
|
2301_79280419/UKUI-quick
|
plugin/ukui-mstm-plugin.h
|
C++
|
unknown
| 273
|
import QtQuick 2.15
import QtQuick.Layouts 1.15
import org.ukui.quick.widgets 1.0
import org.ukui.quick.items 1.0
import QtQuick.Controls 2.15
import QtQuick.Controls 2.15 as Controls
WidgetItem {
id: rootWidget
Layout.preferredWidth: 450
Layout.fillHeight: true
clip: false
RowLayout {
anchors.centerIn: parent
spacing: 10
TextField {
id: microsecondInput
width: 200
placeholderText: "输入微秒数"
validator: RegExpValidator { regExp: /^[0-9]+$/ }
}
Button {
text: "转换"
width: 50
onClicked: {
var microseconds = microsecondInput.text;
var minutes = (microseconds / 60000000).toFixed(6); // 1分钟 = 60,000,000微秒
minuteOutput.text = isNaN(minutes) ? "无效" : minutes.toString();
}
}
Text {
id: minuteOutput
width: 60
horizontalAlignment: Text.AlignHCenter
font.pixelSize: 20
}
}
}
|
2301_79280419/UKUI-quick
|
widget/ui/main.qml
|
QML
|
unknown
| 1,081
|
import numpy as np
import random
import math as mt
class Linear:
def __init__(self,w,b,size):
self.m=size
self.alpha=0.001 #学习率
self.beta1=0.9
self.beta1t=1 #beta1的t次方
self.beta2=0.999
self.beta2t=1
self.mt=np.zeros(2)
self.vt=np.zeros(2)
self.eps=1e-8
self.x_data=[]
self.x_mean=0 #x_data的均值
self.x_std=0 #x_data的标准差
self.y_data=[]
self.y_mean=0
self.y_std=0
self.w=np.zeros(2)
self.data_get(w,b)
def data_get(self,w,b):
x=[random.uniform(-100.0,100.0) for _ in range(self.m)] #随机生成给定数量的[-100,100)数据
y=np.multiply(x,w)+b+np.random.uniform(-1,1,self.m) #按照给定的w和b生成y值并增加一定的噪音
self.x_mean=np.mean(x)
self.x_std=np.std(x)
self.y_mean=np.mean(y)
self.y_std=np.std(y)
self.x_data=[[(x[i]-self.x_mean)/self.x_std,1]for i in range(self.m)] #数据归一化
self.y_data=(y-self.y_mean)/self.y_std
def w_to_w(self):
gradient=np.dot(np.dot(self.x_data,self.w)-self.y_data,self.x_data)/self.m #生成梯度
#mt是梯度的滑动平均,梯度在指向最优解的方向上叠加,在垂直指向最优解方向的方向上抵消
self.mt=self.mt*self.beta1+(1-self.beta1)*gradient
#vt是梯度的变化率的平均,当梯度变化过快时,对应学习率应减小
self.vt=self.vt*self.beta2+(1-self.beta2)*np.multiply(gradient,gradient)
self.beta1t=self.beta1t*self.beta1
self.beta2t=self.beta2t*self.beta2
mt_=self.mt/(1-self.beta1t)
vt_=self.vt/(1-self.beta2t)
self.w=self.w-self.alpha*mt_/(np.sqrt(vt_)+self.eps)
return 1.0/(2*self.m)*np.sum(np.square(np.dot(self.x_data, self.w)-self.y_data))
def linear_regression(self):
time = 0
last_cost=0
while (True):
cost = self.w_to_w()
time = time + 1
print("第{}次梯度下降损失为: {}".format(time, round(cost, 6)))
if mt.fabs(cost-last_cost) < 1e-10:
print(self.w)
return
else: last_cost=cost
#根据线性回归得到的模型预测-100到100数据对应的y值
def predict(self,x):
x=(x-self.x_mean)/self.x_std
res=np.dot([x,1],self.w)
return res*self.y_std+self.y_mean
w=float(input('输入x的系数w:'))
b=float(input('输入对应常数b:'))
size=int(input('输入数据数量:'))
lnreg=Linear(w,b,size)
lnreg.linear_regression()
num=float(input('输入一个x值:(-100<=x<100)'))
print(lnreg.predict(num))
|
2301_79348834/linear_reg
|
线性回归.py
|
Python
|
apache-2.0
| 2,779
|
let searcheText = "皮皮虾" // 搜索关键字,用于在抖音搜索指定用户
let inputText = "你好,我看了你的作品觉得非常喜欢,可以交个朋友吗" // 私信发送的文本内容
// 定义一个查找文本的函数,用于判断指定文本的 TextView 是否存在
function findText(text) {
// 等待并找到所有符合条件的 TextView
var textView
var textViews = className("android.widget.TextView").find()
// 遍历找到的 TextView
for (var i = 0; i < textViews.size(); i++) {
// 记录第几个“已关注”
textView = textViews.get(i)
// 判断 TextView 的文本内容是否为指定文本
if (textView.text() === text) {
// 如果找到,可以执行相应操作,如点击、获取属性等
log("找到文本为 “" + text + "” 的 TextView,index: " + i)
// 例如点击该 TextView
// textView.click()
break // 如果只需要找到第一个匹配的,可以在这里退出循环
}
}
return true
}
// 点击抖音图标,打开抖音应用
click("抖音")
sleep(5000) // 等待应用打开
// 点击“我”按钮,进入个人中心
click("我")
sleep(5000) // 等待页面加载
// 点击“添加朋友”按钮,进入添加朋友页面
click("添加朋友")
sleep(5000) // 等待页面加载
// 点击搜索框,激活输入
click(245, 416)
sleep(5000) // 等待搜索框激活
// 输入搜索文本
setText(searcheText)
sleep(5000) // 等待文本输入完成
// 点击搜索结果中的用户名,进入该用户主页
click("搜索用户名字/抖音号:" + searcheText)
sleep(5000) // 等待用户主页加载
// 点击用户的头像或昵称区域,进入用户详情页面
click(175, 633)
sleep(5000) // 等待页面加载
// 在用户主页找到已关注的文字,判断是否已关注该用户
const text1 = "已关注"
let isFlag = true
if (findText(text1)) { // 如果已关注
sleep(3000)
// 点击“已关注”按钮,展开更多操作选项
click("已关注")
sleep(4000)
// 检查是否出现“取消关注”按钮,确认是否真的已关注
if (findText('取消关注')) {
// 点击“取消关注”按钮,取消关注该用户
click("取消关注")
}
sleep(4000)
isFlag = false // 标记已执行过关注操作
}
sleep(10000) // 等待页面状态稳定
// 如果之前未关注该用户,则执行关注操作
if (!isFlag) {
// 点击“关注”按钮,关注该用户
click("关注", 1)
}
sleep(7000) // 等待关注操作完成
// 点击“私信”按钮,打开私信聊天窗口
click("私信", 1)
sleep(5000) // 等待聊天窗口打开
// 点击输入框,激活输入
click(213, 2611)
sleep(5000) // 等待输入框激活
// 输入要发送的私信内容
setText(inputText)
sleep(5000) // 等待文本输入完成
// 点击发送按钮,发送私信
click(1150, 1598)
|
2301_78992106/oneChat
|
index.js
|
JavaScript
|
unknown
| 3,092
|
/**
* @file: selfCloseInputTag.js
* @desc: 遍历指定目录下 .ux 文件,将其中 input 标签由 <input **></input> 转换为 <input ** />
* @date: 2019-01-23
*/
const fs = require('fs')
const path = require('path')
const quickappCodePath = './src/'
const main = codePath => {
const traversing = cpath => {
const files = fs.readdirSync(cpath)
files.forEach(fileName => {
const fPath = path.join(cpath, fileName)
const stats = fs.statSync(fPath)
stats.isDirectory() && traversing(fPath)
stats.isFile() && fPath.endsWith('.ux') && matchAndReplace(fPath)
})
}
traversing(codePath)
}
const matchAndReplace = path => {
const pageContent = fs.readFileSync(path, 'UTF-8')
const newContent = pageContent.replace(
/(<)([\s]*?)(input\b[^\/]*?)>[\s\S]*?<\/input>/gm,
'$1$3 />'
)
fs.writeFile(path, newContent, error => {
if (error) throw `Something went wrong: ${error}`
})
}
main(quickappCodePath)
|
2301_79280419/ai-drive-tool
|
scripts/selfCloseInputTag.js
|
JavaScript
|
unknown
| 968
|
.flex-box-mixins (@column, @justify, @align) {
flex-direction: @column;
justify-content: @justify;
align-items: @align;
}
|
2301_79280419/ai-drive-tool
|
src/assets/styles/mixins.less
|
Less
|
unknown
| 127
|
@import './variables.less';
@import './mixins.less';
|
2301_79280419/ai-drive-tool
|
src/assets/styles/style.less
|
Less
|
unknown
| 53
|
@brand: #09ba07;
@white: #ffffff;
@black: #000000;
@grey: #9393aa;
@red: #fa0101;
@green: #ffff00;
@size-factor: 5px;
|
2301_79280419/ai-drive-tool
|
src/assets/styles/variables.less
|
Less
|
unknown
| 120
|
/**
* 封装了一些网络请求方法,方便通过 Promise 的形式请求接口
*/
import $fetch from '@system.fetch'
import { queryString } from './utils'
const TIMEOUT = 300000
Promise.prototype.finally = function(callback) {
const P = this.constructor
return this.then(
value => P.resolve(callback()).then(() => value),
reason =>
P.resolve(callback()).then(() => {
throw reason
})
)
}
/**
* 调用快应用 fetch 接口做网络请求
* @param params
*/
function fetchPromise(params) {
return new Promise((resolve, reject) => {
$fetch
.fetch({
url: params.url,
method: params.method,
data: params.data,
header:{'Content-Type':'application/json'}
})
.then(response => {
const result = response.data
// const content = JSON.parse(result.data)
/* @desc: 可跟具体不同业务接口数据,返回你所需要的部分,使得使用尽可能便捷 */
// content.data ? resolve(content) : resolve(content.message)
resolve(result)
})
.catch((error, code) => {
console.log(`🐛 request fail, code = ${code}`)
reject(error)
})
.finally(() => {
console.log(`✔️ request @${params.url} has been completed.`)
resolve()
})
})
}
/**
* 处理网络请求,timeout 是网络请求超时之后返回,默认 20s 可自行修改
* @param params
*/
function requestHandle(params, timeout = TIMEOUT) {
try {
return Promise.race([
fetchPromise(params),
new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('网络状况不太好,再刷新一次?'))
}, timeout)
})
])
} catch (error) {
console.log(error)
}
}
export default {
post: function(url, params) {
return requestHandle({
method: 'post',
url: url,
data: params
})
},
get: function(url, params) {
return requestHandle({
method: 'get',
url: queryString(url, params)
})
},
put: function(url, params) {
return requestHandle({
method: 'put',
url: url,
data: params
})
}
// 如果,method 您需要更多类型,可自行添加更多方法;
}
|
2301_79280419/ai-drive-tool
|
src/helper/ajax.js
|
JavaScript
|
unknown
| 2,271
|
import $ajax from '../ajax'
/**
* @desc 在实际开发中,您可以将 baseUrl 替换为您的请求地址前缀;
* 备注:如果您不需要发起请求,删除 apis 目录,以及 app.ux 中引用即可;
*/
const baseUrl ="http://csreu8fhri0c73d83hjg-3008.agent.damodel.com"
//ai接口
export function getTranslate(data){
return $ajax.post(baseUrl+'/translate',data)
}
|
2301_79280419/ai-drive-tool
|
src/helper/apis/example.js
|
JavaScript
|
unknown
| 392
|
/**
* 您可以将常用的方法、或系统 API,统一封装,暴露全局,以便各页面、组件调用,而无需 require / import.
*/
import prompt from '@system.prompt';
/**
* 拼接 url 和参数
*/
export function queryString(url, query) {
let str = [];
for (let key in query) {
str.push(key + '=' + query[key]);
}
let paramStr = str.join('&');
return paramStr ? `${url}?${paramStr}` : url;
}
export function showToast(message = '', duration = 0) {
if (!message) return;
prompt.showToast({
message: message,
duration
});
}
|
2301_79280419/ai-drive-tool
|
src/helper/utils.js
|
JavaScript
|
unknown
| 591
|
/**
* @file: selfCloseInputTag.js
* @desc: 遍历指定目录下 .ux 文件,将其中 input 标签由 <input **></input> 转换为 <input ** />
* @date: 2019-01-23
*/
const fs = require('fs')
const path = require('path')
const quickappCodePath = './src/'
const main = codePath => {
const traversing = cpath => {
const files = fs.readdirSync(cpath)
files.forEach(fileName => {
const fPath = path.join(cpath, fileName)
const stats = fs.statSync(fPath)
stats.isDirectory() && traversing(fPath)
stats.isFile() && fPath.endsWith('.ux') && matchAndReplace(fPath)
})
}
traversing(codePath)
}
const matchAndReplace = path => {
const pageContent = fs.readFileSync(path, 'UTF-8')
const newContent = pageContent.replace(
/(<)([\s]*?)(input\b[^\/]*?)>[\s\S]*?<\/input>/gm,
'$1$3 />'
)
fs.writeFile(path, newContent, error => {
if (error) throw `Something went wrong: ${error}`
})
}
main(quickappCodePath)
|
2301_79280419/ai-food-plan
|
scripts/selfCloseInputTag.js
|
JavaScript
|
unknown
| 968
|
.flex-box-mixins (@column, @justify, @align) {
flex-direction: @column;
justify-content: @justify;
align-items: @align;
}
|
2301_79280419/ai-food-plan
|
src/assets/styles/mixins.less
|
Less
|
unknown
| 127
|
@import './variables.less';
@import './mixins.less';
|
2301_79280419/ai-food-plan
|
src/assets/styles/style.less
|
Less
|
unknown
| 53
|
@brand: #09ba07;
@white: #ffffff;
@black: #000000;
@grey: #9393aa;
@red: #fa0101;
@green: #ffff00;
@size-factor: 5px;
|
2301_79280419/ai-food-plan
|
src/assets/styles/variables.less
|
Less
|
unknown
| 120
|
/**
* 封装了一些网络请求方法,方便通过 Promise 的形式请求接口
*/
import $fetch from '@system.fetch'
import { queryString } from './utils'
const TIMEOUT = 300000
Promise.prototype.finally = function(callback) {
const P = this.constructor
return this.then(
value => P.resolve(callback()).then(() => value),
reason =>
P.resolve(callback()).then(() => {
throw reason
})
)
}
/**
* 调用快应用 fetch 接口做网络请求
* @param params
*/
function fetchPromise(params) {
return new Promise((resolve, reject) => {
$fetch
.fetch({
url: params.url,
method: params.method,
data: params.data,
header:{'Content-Type':'application/json'}
})
.then(response => {
const result = response.data
// const content = JSON.parse(result.data)
/* @desc: 可跟具体不同业务接口数据,返回你所需要的部分,使得使用尽可能便捷 */
// content.data ? resolve(content) : resolve(content.message)
resolve(result)
})
.catch((error, code) => {
console.log(`🐛 request fail, code = ${code}`)
reject(error)
})
.finally(() => {
console.log(`✔️ request @${params.url} has been completed.`)
resolve()
})
})
}
/**
* 处理网络请求,timeout 是网络请求超时之后返回,默认 20s 可自行修改
* @param params
*/
function requestHandle(params, timeout = TIMEOUT) {
try {
return Promise.race([
fetchPromise(params),
new Promise((resolve, reject) => {
setTimeout(() => {
reject(new Error('网络状况不太好,再刷新一次?'))
}, timeout)
})
])
} catch (error) {
console.log(error)
}
}
export default {
post: function(url, params) {
return requestHandle({
method: 'post',
url: url,
data: params
})
},
get: function(url, params) {
return requestHandle({
method: 'get',
url: queryString(url, params)
})
},
put: function(url, params) {
return requestHandle({
method: 'put',
url: url,
data: params
})
}
// 如果,method 您需要更多类型,可自行添加更多方法;
}
|
2301_79280419/ai-food-plan
|
src/helper/ajax.js
|
JavaScript
|
unknown
| 2,271
|
import $ajax from '../ajax'
/**
* @desc 在实际开发中,您可以将 baseUrl 替换为您的请求地址前缀;
* 备注:如果您不需要发起请求,删除 apis 目录,以及 app.ux 中引用即可;
*/
const baseUrl ="http://csreu8fhri0c73d83hjg-3008.agent.damodel.com"
//ai
export function getTranslate(data){
return $ajax.post(baseUrl+'/translate',data)
}
|
2301_79280419/ai-food-plan
|
src/helper/apis/example.js
|
JavaScript
|
unknown
| 386
|
/**
* 您可以将常用的方法、或系统 API,统一封装,暴露全局,以便各页面、组件调用,而无需 require / import.
*/
import prompt from '@system.prompt';
/**
* 拼接 url 和参数
*/
export function queryString(url, query) {
let str = [];
for (let key in query) {
str.push(key + '=' + query[key]);
}
let paramStr = str.join('&');
return paramStr ? `${url}?${paramStr}` : url;
}
export function showToast(message = '', duration = 0) {
if (!message) return;
prompt.showToast({
message: message,
duration
});
}
|
2301_79280419/ai-food-plan
|
src/helper/utils.js
|
JavaScript
|
unknown
| 591
|
"""
音频格式转换工具
支持将.m4a格式转换为.wav格式
"""
import os
import subprocess
import tempfile
from pathlib import Path
from typing import Optional, Tuple
import logging
# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
class AudioConverter:
"""音频格式转换器"""
def __init__(self):
"""初始化转换器"""
self.supported_input_formats = ['.m4a', '.mp3', '.aac', '.flac', '.ogg', '.wav']
self.output_format = '.wav'
def check_ffmpeg_available(self) -> bool:
"""检查FFmpeg是否可用"""
try:
result = subprocess.run(['ffmpeg', '-version'],
capture_output=True, text=True, timeout=10)
return result.returncode == 0
except (subprocess.TimeoutExpired, FileNotFoundError):
return False
def convert_to_wav(self, input_path: str, output_path: Optional[str] = None) -> Tuple[bool, str]:
"""
将音频文件转换为WAV格式
Args:
input_path: 输入文件路径
output_path: 输出文件路径(可选,默认在同目录生成)
Returns:
Tuple[bool, str]: (是否成功, 输出文件路径或错误信息)
"""
try:
input_file = Path(input_path)
# 检查输入文件是否存在
if not input_file.exists():
return False, f"输入文件不存在: {input_path}"
# 检查文件格式
if input_file.suffix.lower() not in self.supported_input_formats:
return False, f"不支持的文件格式: {input_file.suffix}"
# 如果已经是WAV格式,直接返回原路径
if input_file.suffix.lower() == '.wav':
logger.info(f"文件已经是WAV格式: {input_path}")
return True, input_path
# 检查FFmpeg是否可用
if not self.check_ffmpeg_available():
return False, "FFmpeg未安装或不可用,请先安装FFmpeg"
# 确定输出路径
if output_path is None:
output_path = str(input_file.with_suffix('.wav'))
output_file = Path(output_path)
# 创建输出目录(如果不存在)
output_file.parent.mkdir(parents=True, exist_ok=True)
# 构建FFmpeg命令
cmd = [
'ffmpeg',
'-i', str(input_file), # 输入文件
'-acodec', 'pcm_s16le', # 音频编码器
'-ar', '16000', # 采样率 16kHz
'-ac', '1', # 单声道
'-y', # 覆盖输出文件
str(output_file) # 输出文件
]
logger.info(f"开始转换: {input_file.name} -> {output_file.name}")
# 执行转换
result = subprocess.run(cmd, capture_output=True, text=True, timeout=300)
if result.returncode == 0:
# 检查输出文件是否生成
if output_file.exists() and output_file.stat().st_size > 0:
logger.info(f"转换成功: {output_file}")
return True, str(output_file)
else:
return False, "转换失败:输出文件未生成或为空"
else:
error_msg = result.stderr or result.stdout or "未知错误"
logger.error(f"FFmpeg转换失败: {error_msg}")
return False, f"转换失败: {error_msg}"
except subprocess.TimeoutExpired:
return False, "转换超时(超过5分钟)"
except Exception as e:
logger.error(f"转换过程中发生错误: {str(e)}")
return False, f"转换错误: {str(e)}"
def convert_with_temp_file(self, input_path: str) -> Tuple[bool, str]:
"""
转换音频文件并使用临时文件
Args:
input_path: 输入文件路径
Returns:
Tuple[bool, str]: (是否成功, 临时WAV文件路径或错误信息)
"""
try:
input_file = Path(input_path)
# 如果已经是WAV格式,直接返回原路径
if input_file.suffix.lower() == '.wav':
return True, input_path
# 创建临时文件
with tempfile.NamedTemporaryFile(suffix='.wav', delete=False) as temp_file:
temp_path = temp_file.name
# 执行转换
success, result = self.convert_to_wav(input_path, temp_path)
if success:
return True, temp_path
else:
# 清理临时文件
try:
os.unlink(temp_path)
except:
pass
return False, result
except Exception as e:
return False, f"临时文件转换错误: {str(e)}"
def get_audio_info(self, file_path: str) -> dict:
"""
获取音频文件信息
Args:
file_path: 音频文件路径
Returns:
dict: 音频文件信息
"""
try:
if not self.check_ffmpeg_available():
return {"error": "FFmpeg不可用"}
cmd = [
'ffprobe',
'-v', 'quiet',
'-print_format', 'json',
'-show_format',
'-show_streams',
file_path
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=30)
if result.returncode == 0:
import json
info = json.loads(result.stdout)
return info
else:
return {"error": f"获取音频信息失败: {result.stderr}"}
except Exception as e:
return {"error": f"获取音频信息错误: {str(e)}"}
def convert_to_wav_compressed(self, input_path: str, output_path: Optional[str] = None,
target_size_mb: int = 30) -> Tuple[bool, str]:
"""
将音频文件转换为压缩的WAV格式,控制文件大小
Args:
input_path: 输入文件路径
output_path: 输出文件路径(可选)
target_size_mb: 目标文件大小(MB)
Returns:
Tuple[bool, str]: (是否成功, 输出文件路径或错误信息)
"""
try:
input_file = Path(input_path)
# 检查输入文件
if not input_file.exists():
return False, f"输入文件不存在: {input_path}"
# 检查文件格式
if input_file.suffix.lower() not in self.supported_input_formats:
return False, f"不支持的文件格式: {input_file.suffix}"
# 检查FFmpeg
if not self.check_ffmpeg_available():
return False, "FFmpeg未安装或不可用"
# 确定输出路径
if output_path is None:
output_path = str(input_file.with_suffix('_compressed.wav'))
output_file = Path(output_path)
output_file.parent.mkdir(parents=True, exist_ok=True)
# 获取音频信息
audio_info = self.get_audio_info(str(input_file))
if "error" in audio_info:
return False, audio_info["error"]
# 计算压缩参数
duration = audio_info.get("duration", 0)
if duration == 0:
return False, "无法获取音频时长"
# 计算目标比特率 (kbps)
# 目标大小(MB) * 8(bits/byte) * 1024(KB/MB) / 时长(秒)
target_bitrate = int((target_size_mb * 8 * 1024) / duration)
target_bitrate = max(32, min(target_bitrate, 128)) # 限制在32-128kbps之间
# 构建压缩转换命令
cmd = [
'ffmpeg',
'-i', str(input_file),
'-acodec', 'pcm_s16le',
'-ar', '16000', # 降低采样率到16kHz
'-ac', '1', # 单声道
'-ab', f'{target_bitrate}k', # 设置比特率
'-y',
str(output_file)
]
logger.info(f"开始压缩转换: {input_file.name} -> {output_file.name} (目标: {target_size_mb}MB, 比特率: {target_bitrate}kbps)")
# 执行转换
result = subprocess.run(cmd, capture_output=True, text=True, timeout=600)
if result.returncode == 0 and output_file.exists():
# 检查压缩后的文件大小
compressed_size_mb = output_file.stat().st_size / (1024 * 1024)
logger.info(f"压缩完成: {compressed_size_mb:.1f}MB")
return True, str(output_file)
else:
error_msg = result.stderr or "转换失败"
logger.error(f"压缩转换失败: {error_msg}")
return False, f"压缩转换失败: {error_msg}"
except subprocess.TimeoutExpired:
return False, "压缩转换超时(超过10分钟)"
except Exception as e:
logger.error(f"压缩转换过程中发生错误: {str(e)}")
return False, f"压缩转换错误: {str(e)}"
def convert_audio_file(input_path: str, output_path: Optional[str] = None) -> Tuple[bool, str]:
"""
便捷函数:转换音频文件为WAV格式
Args:
input_path: 输入文件路径
output_path: 输出文件路径(可选)
Returns:
Tuple[bool, str]: (是否成功, 输出文件路径或错误信息)
"""
converter = AudioConverter()
return converter.convert_to_wav(input_path, output_path)
if __name__ == "__main__":
# 测试代码
converter = AudioConverter()
# 检查FFmpeg
if converter.check_ffmpeg_available():
print("✓ FFmpeg可用")
else:
print("✗ FFmpeg不可用,请先安装FFmpeg")
exit(1)
# 测试转换(如果有测试文件)
test_file = "recordings/4.24公司晨会.m4a"
if os.path.exists(test_file):
print(f"\n测试转换文件: {test_file}")
success, result = converter.convert_to_wav(test_file)
if success:
print(f"✓ 转换成功: {result}")
else:
print(f"✗ 转换失败: {result}")
else:
print(f"\n测试文件不存在: {test_file}")
|
2301_79424223/GitCode
|
audio_converter.py
|
Python
|
unknown
| 11,108
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
音频录制模块
提供录音功能的核心类
"""
import sounddevice as sd
import numpy as np
import wave
import threading
import time
from datetime import datetime
import os
class AudioRecorder:
def __init__(self, sample_rate=16000, channels=1, dtype=np.float32):
"""
初始化录音器
Args:
sample_rate (int): 采样率,默认16000Hz
channels (int): 声道数,默认1(单声道)
dtype: 数据类型,默认float32
"""
self.sample_rate = sample_rate
self.channels = channels
self.dtype = dtype
self.recording = False
self.audio_data = []
self.record_thread = None
def start_recording(self):
"""
开始录音
"""
if self.recording:
raise RuntimeError("录音已在进行中")
self.recording = True
self.audio_data = []
# 启动录音线程
self.record_thread = threading.Thread(target=self._record_audio)
self.record_thread.daemon = True
self.record_thread.start()
def stop_recording(self, output_file=None):
"""
停止录音并保存文件
Args:
output_file (str): 输出文件路径,如果为None则自动生成
Returns:
str: 保存的文件路径
"""
if not self.recording:
raise RuntimeError("当前没有在录音")
self.recording = False
# 等待录音线程结束
if self.record_thread and self.record_thread.is_alive():
self.record_thread.join(timeout=2.0)
# 生成输出文件名
if output_file is None:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
output_file = f"recording_{timestamp}.wav"
# 保存音频文件
if self.audio_data:
self._save_audio(output_file)
return output_file
else:
raise RuntimeError("没有录制到音频数据")
def is_recording(self):
"""
检查是否正在录音
Returns:
bool: 是否正在录音
"""
return self.recording
def get_available_devices(self):
"""
获取可用的音频设备
Returns:
dict: 设备信息
"""
try:
devices = sd.query_devices()
return devices
except Exception as e:
print(f"获取设备信息失败: {e}")
return None
def _record_audio(self):
"""
录音线程函数
"""
try:
# 使用sounddevice录音
with sd.InputStream(
samplerate=self.sample_rate,
channels=self.channels,
dtype=self.dtype,
callback=self._audio_callback
) as stream:
while self.recording:
time.sleep(0.1)
except Exception as e:
print(f"录音过程中发生错误: {e}")
self.recording = False
def _audio_callback(self, indata, frames, time, status):
"""
音频回调函数
Args:
indata: 输入音频数据
frames: 帧数
time: 时间信息
status: 状态信息
"""
if status:
print(f"音频回调状态: {status}")
if self.recording:
# 将音频数据添加到缓冲区
self.audio_data.append(indata.copy())
def _save_audio(self, filename):
"""
保存音频文件
Args:
filename (str): 文件名
"""
if not self.audio_data:
raise ValueError("没有音频数据可保存")
# 合并所有音频数据
audio_array = np.concatenate(self.audio_data, axis=0)
# 确保目录存在
os.makedirs(os.path.dirname(filename) if os.path.dirname(filename) else '.', exist_ok=True)
# 保存为WAV文件
with wave.open(filename, 'wb') as wf:
wf.setnchannels(self.channels)
wf.setsampwidth(4) # float32 = 4 bytes
wf.setframerate(self.sample_rate)
# 转换为16位整数格式保存
audio_int16 = (audio_array * 32767).astype(np.int16)
wf.setsampwidth(2) # 16位 = 2 bytes
wf.writeframes(audio_int16.tobytes())
print(f"音频已保存到: {filename}")
# 测试函数
def test_recorder():
"""
测试录音功能
"""
recorder = AudioRecorder()
print("开始录音...")
recorder.start_recording()
# 录音5秒
time.sleep(5)
print("停止录音...")
output_file = recorder.stop_recording()
print(f"录音已保存到: {output_file}")
if __name__ == "__main__":
test_recorder()
|
2301_79424223/GitCode
|
audio_recorder.py
|
Python
|
unknown
| 5,193
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
全自动化工作流程模块
实现录音→转文本→生成摘要→推送飞书的完整自动化流程
"""
import os
import json
import time
import subprocess
from datetime import datetime
from pathlib import Path
from config import get_config
from speech_recognition import SpeechRecognizer
from llm_processor import LLMProcessor
class AutomationWorkflow:
"""自动化工作流程管理器"""
def __init__(self):
"""初始化工作流程"""
self.config = get_config()
self.speech_recognizer = None
self.llm_processor = None
# 初始化各个组件
self._initialize_components()
def _initialize_components(self):
"""初始化各个处理组件"""
try:
# 初始化语音识别器
if self.config.SPEECH_API_TOKEN and self.config.SPEECH_API_URL:
self.speech_recognizer = SpeechRecognizer(
api_key=self.config.SPEECH_API_TOKEN,
api_url=self.config.SPEECH_API_URL
)
print("✓ 语音识别器初始化成功")
else:
print("✗ 语音识别器初始化失败:缺少SPEECH_API_TOKEN或SPEECH_API_URL")
# 初始化大模型处理器
if all([self.config.LLM_API_KEY, self.config.LLM_BASE_URL, self.config.LLM_MODEL_NAME]):
self.llm_processor = LLMProcessor(
api_key=self.config.LLM_API_KEY,
base_url=self.config.LLM_BASE_URL,
model_name=self.config.LLM_MODEL_NAME
)
self.llm_processor.set_temperature(self.config.LLM_TEMPERATURE)
print("✓ 大模型处理器初始化成功")
else:
print("✗ 大模型处理器初始化失败:缺少必要的API配置")
except Exception as e:
print(f"组件初始化异常: {str(e)}")
def process_audio_file(self, audio_file_path, auto_push=None):
"""
处理单个音频文件的完整流程
Args:
audio_file_path (str): 音频文件路径
auto_push (bool): 是否自动推送到飞书,None则使用配置文件设置
Returns:
dict: 处理结果
"""
if auto_push is None:
auto_push = self.config.AUTO_PUSH_TO_FEISHU
print(f"\n{'='*50}")
print(f"开始处理音频文件: {os.path.basename(audio_file_path)}")
print(f"{'='*50}")
# 生成文件名(基于音频文件名)
base_name = Path(audio_file_path).stem
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
transcript_file = self.config.get_transcript_file_path(f"{base_name}_{timestamp}.json")
summary_file = self.config.get_summary_file_path(f"{base_name}_{timestamp}.json")
result = {
"audio_file": audio_file_path,
"transcript_file": transcript_file,
"summary_file": summary_file,
"timestamp": timestamp,
"steps": {}
}
try:
# 步骤1: 语音转文本
print("\n🎵 步骤1: 语音转文本...")
if not self.speech_recognizer:
raise Exception("语音识别器未初始化")
transcript_result = self.speech_recognizer.recognize_file(
audio_file_path,
transcript_file
)
if transcript_result.get("status") != "success":
raise Exception(f"语音识别失败: {transcript_result.get('error', '未知错误')}")
transcript_text = transcript_result.get("text", "")
result["steps"]["speech_recognition"] = {
"status": "success",
"text_length": len(transcript_text),
"file": transcript_file
}
print(f"✓ 语音转文本完成,文本长度: {len(transcript_text)} 字符")
# 步骤2: 生成摘要和标题
print("\n🤖 步骤2: 生成摘要和标题...")
if not self.llm_processor:
raise Exception("大模型处理器未初始化")
if not transcript_text.strip():
raise Exception("转录文本为空,无法生成摘要")
summary_result = self.llm_processor.generate_summary_and_title(
transcript_text,
summary_file
)
if summary_result.get("status") != "success":
raise Exception(f"摘要生成失败: {summary_result.get('error', '未知错误')}")
result["steps"]["llm_processing"] = {
"status": "success",
"title": summary_result.get("title", ""),
"summary": summary_result.get("summary", ""),
"summary_length": len(summary_result.get("summary", "")),
"file": summary_file
}
print(f"✓ 摘要和标题生成完成")
print(f" 标题: {summary_result.get('title', 'N/A')}")
# 步骤3: 推送到飞书
if auto_push:
print("\n📤 步骤3: 推送到飞书...")
push_result = self._push_to_feishu(summary_result, base_name)
result["steps"]["feishu_push"] = push_result
if push_result.get("status") == "success":
print("✓ 飞书推送完成")
else:
print(f"✗ 飞书推送失败: {push_result.get('error', '未知错误')}")
else:
print("\n📤 步骤3: 跳过飞书推送(根据配置)")
result["steps"]["feishu_push"] = {"status": "skipped"}
# 步骤4: 清理临时文件(可选)
if self.config.DELETE_TEMP_FILES:
print("\n🗑️ 步骤4: 清理临时文件...")
self._cleanup_temp_files([transcript_file])
result["steps"]["cleanup"] = {"status": "success"}
else:
result["steps"]["cleanup"] = {"status": "skipped"}
result["status"] = "success"
print(f"\n✅ 音频文件处理完成: {os.path.basename(audio_file_path)}")
except Exception as e:
error_msg = f"处理音频文件时发生异常: {str(e)}"
print(f"\n❌ {error_msg}")
result["status"] = "error"
result["error"] = error_msg
return result
def _push_to_feishu(self, summary_data, base_name):
"""
推送数据到飞书
Args:
summary_data (dict): 摘要数据
base_name (str): 基础文件名
Returns:
dict: 推送结果
"""
try:
# 准备推送数据 - 确保只推送干净的title和summary
title = summary_data.get("title", f"{base_name}_摘要")
summary = summary_data.get("summary", "")
# 如果summary是列表,转换为格式化字符串
if isinstance(summary, list):
summary = "\n".join([f"{i+1}. {item}" for i, item in enumerate(summary)])
# 确保summary是字符串且不包含解析说明
if isinstance(summary, str):
# 移除可能的markdown代码块和解析说明
if "```json" in summary or "### 解析" in summary or "根据录音内容" in summary:
summary = "摘要内容格式异常,请检查LLM响应"
push_data = {
"title": title,
"summary": summary,
"timestamp": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"source": base_name
}
print(f"[DEBUG] 准备推送的数据:")
print(f" 标题: {push_data['title']}")
print(f" 摘要长度: {len(push_data['summary'])} 字符")
print(f" 摘要预览: {push_data['summary'][:100]}...")
# 将数据写入临时文件供Node.js脚本使用
temp_summary_file = os.path.join(self.config.SUMMARIES_DIR, "temp_push_data.json")
with open(temp_summary_file, 'w', encoding='utf-8') as f:
json.dump(push_data, f, ensure_ascii=False, indent=2)
# 推送脚本路径
push_script = os.path.join(self.config.BITABLE_DIR, "快速推送.js")
if not os.path.exists(push_script):
return {
"status": "error",
"error": f"推送脚本不存在: {push_script}"
}
# 执行推送脚本
print(f"正在执行推送脚本: {push_script}")
result = subprocess.run(
["node", push_script],
cwd=self.config.BITABLE_DIR,
capture_output=True,
text=True,
encoding='utf-8', # 明确指定UTF-8编码
errors='replace', # 遇到编码错误时替换为占位符
timeout=60 # 60秒超时
)
print(f"推送脚本返回码: {result.returncode}")
print(f"推送脚本标准输出: {result.stdout}")
print(f"推送脚本错误输出: {result.stderr}")
if result.returncode == 0:
return {
"status": "success",
"output": result.stdout,
"stderr": result.stderr,
"temp_file": temp_summary_file
}
else:
return {
"status": "error",
"error": f"推送脚本执行失败 (返回码: {result.returncode})",
"stdout": result.stdout,
"stderr": result.stderr,
"temp_file": temp_summary_file
}
except subprocess.TimeoutExpired:
return {
"status": "error",
"error": "推送脚本执行超时"
}
except Exception as e:
return {
"status": "error",
"error": f"推送过程中发生异常: {str(e)}"
}
def _cleanup_temp_files(self, file_list):
"""
清理临时文件
Args:
file_list (list): 要删除的文件列表
"""
for file_path in file_list:
try:
if os.path.exists(file_path):
os.remove(file_path)
print(f" 删除临时文件: {os.path.basename(file_path)}")
except Exception as e:
print(f" 删除文件失败 {file_path}: {str(e)}")
def batch_process_recordings(self, recordings_dir=None):
"""
批量处理录音目录中的所有音频文件
Args:
recordings_dir (str): 录音目录路径,None则使用配置的默认目录
Returns:
list: 处理结果列表
"""
if recordings_dir is None:
recordings_dir = self.config.RECORDINGS_DIR
print(f"\n开始批量处理录音目录: {recordings_dir}")
# 支持的音频格式
audio_extensions = ['.wav', '.mp3', '.m4a', '.flac', '.aac']
# 查找所有音频文件
audio_files = []
for ext in audio_extensions:
audio_files.extend(Path(recordings_dir).glob(f"*{ext}"))
if not audio_files:
print("未找到任何音频文件")
return []
print(f"找到 {len(audio_files)} 个音频文件")
results = []
for i, audio_file in enumerate(audio_files, 1):
print(f"\n处理进度: {i}/{len(audio_files)}")
result = self.process_audio_file(str(audio_file))
results.append(result)
# 处理间隔(避免API调用过于频繁)
if i < len(audio_files):
time.sleep(2)
# 统计结果
success_count = sum(1 for r in results if r.get("status") == "success")
print(f"\n批量处理完成:")
print(f" 总文件数: {len(results)}")
print(f" 成功处理: {success_count}")
print(f" 处理失败: {len(results) - success_count}")
return results
def get_status(self):
"""
获取工作流程状态
Returns:
dict: 状态信息
"""
return {
"speech_recognizer_ready": self.speech_recognizer is not None,
"llm_processor_ready": self.llm_processor is not None,
"auto_process_enabled": self.config.AUTO_PROCESS_ENABLED,
"auto_push_enabled": self.config.AUTO_PUSH_TO_FEISHU,
"recordings_dir": self.config.RECORDINGS_DIR,
"transcripts_dir": self.config.TRANSCRIPTS_DIR,
"summaries_dir": self.config.SUMMARIES_DIR
}
def test_workflow():
"""测试自动化工作流程"""
workflow = AutomationWorkflow()
print("工作流程状态:")
status = workflow.get_status()
for key, value in status.items():
print(f" {key}: {value}")
# 如果有测试音频文件,可以进行测试
test_audio = os.path.join(workflow.config.RECORDINGS_DIR, "test.wav")
if os.path.exists(test_audio):
print(f"\n测试处理音频文件: {test_audio}")
result = workflow.process_audio_file(test_audio, auto_push=False)
print("测试结果:", json.dumps(result, ensure_ascii=False, indent=2))
else:
print(f"\n测试音频文件不存在: {test_audio}")
print("请将测试音频文件放置在recordings目录下")
if __name__ == "__main__":
test_workflow()
|
2301_79424223/GitCode
|
automation_workflow.py
|
Python
|
unknown
| 14,335
|
const client = require("./client");
const spinner = require("./spinner");
const lark = require('@larksuiteoapi/node-sdk');
const addTable = async (app_token, table) => {
const execSpinner = spinner("创建中");
try {
const options = {};
if (client.userAccessToken) {
Object.assign(options, lark.withUserAccessToken(client.userAccessToken));
}
const { data } = await client.bitable.appTable.create({
path: {
app_token: app_token,
},
data: {
table: table,
},
}, options);
execSpinner.succeed("创建成功");
return data;
} catch (e) {
execSpinner.fail("创建失败");
}
};
module.exports = addTable;
|
2301_79424223/GitCode
|
bitable/addTable.js
|
JavaScript
|
unknown
| 688
|
const client = require("./client");
const spinner = require("./spinner");
const lark = require('@larksuiteoapi/node-sdk');
const addTableRecord = async (app_token, table_id, records) => {
const execSpinner = spinner("添加中");
try {
const options = {};
if (client.userAccessToken) {
Object.assign(options, lark.withUserAccessToken(client.userAccessToken));
}
const { data } = await client.bitable.appTableRecord.batchCreate({
path: {
app_token: app_token,
table_id: table_id,
},
data: {
records: records,
},
}, options);
execSpinner.succeed("添加成功");
return data;
} catch (e) {
execSpinner.fail("添加失败");
}
};
module.exports = addTableRecord;
|
2301_79424223/GitCode
|
bitable/addTableRecord.js
|
JavaScript
|
unknown
| 755
|
const lark = require("@larksuiteoapi/node-sdk");
// 示例配置文件
// 请复制此文件为 client.js 并填入真实的凭证信息
const client = new lark.Client({
appId: "cli_xxxxxxxxxxxxxxxxx", // 替换为你的App ID
appSecret: "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx", // 替换为你的App Secret
appType: lark.AppType.SelfBuild,
domain: lark.Domain.Feishu
});
// 可选:配置用户访问凭证,推荐配置以获得更好的权限体验
// 如果配置了此项,创建的多维表格将属于用户,用户可以直接编辑管理
client.userAccessToken = "u-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"; // 替换为你的user_access_token
module.exports = client;
/*
配置说明:
1. appId: 在飞书开发者后台 -> 应用详情 -> 凭证与基础信息 中获取
2. appSecret: 在飞书开发者后台 -> 应用详情 -> 凭证与基础信息 中获取
3. userAccessToken: 在API调试台中获取,可选但推荐配置
获取userAccessToken的步骤:
1. 访问 https://open.feishu.cn/document/server-docs/docs/bitable-v1/app/create
2. 在右侧调试台确保Authorization选择为 user_access_token
3. 点击「获取Token」
4. 在弹窗中点击「确认添加」
5. 复制生成的token
*/
|
2301_79424223/GitCode
|
bitable/client.example.js
|
JavaScript
|
unknown
| 1,224
|
const lark = require("@larksuiteoapi/node-sdk");
const fs = require('fs');
const path = require('path');
// 读取.env文件
function loadEnvConfig() {
try {
const envPath = path.join(__dirname, '../.env');
const envContent = fs.readFileSync(envPath, 'utf8');
const envVars = {};
envContent.split('\n').forEach(line => {
const trimmedLine = line.trim();
if (trimmedLine && !trimmedLine.startsWith('#')) {
const [key, ...valueParts] = trimmedLine.split('=');
if (key && valueParts.length > 0) {
envVars[key.trim()] = valueParts.join('=').trim();
}
}
});
return envVars;
} catch (error) {
console.error('读取.env文件失败:', error.message);
return {};
}
}
const envVars = loadEnvConfig();
const client = new lark.Client({
appId: envVars.FEISHU_APP_ID || "cli_a85b801777ad500b",
appSecret: envVars.FEISHU_APP_SECRET || "IWokuQK0qh0wMixQ8wFUMbBOd2LsY16n",
appType: lark.AppType.SelfBuild,
domain: lark.Domain.Feishu,
});
// 设置用户访问令牌(如果配置了的话)
if (envVars.FEISHU_USER_ACCESS_TOKEN) {
client.userAccessToken = envVars.FEISHU_USER_ACCESS_TOKEN;
}
module.exports = client;
|
2301_79424223/GitCode
|
bitable/client.js
|
JavaScript
|
unknown
| 1,217
|
const client = require("./client");
const spinner = require("./spinner");
const lark = require("@larksuiteoapi/node-sdk");
const createTable = async (body) => {
const execSpinner = spinner("创建中");
try {
const requestOptions = {};
if (client.userAccessToken) {
Object.assign(requestOptions, lark.withUserAccessToken(client.userAccessToken));
}
const { data } = await client.bitable.app.create(
{
data: body,
},
requestOptions
);
execSpinner.succeed("创建成功");
return data;
} catch (e) {
execSpinner.fail("创建失败");
}
};
module.exports = createTable;
|
2301_79424223/GitCode
|
bitable/createTable.js
|
JavaScript
|
unknown
| 643
|
const client = require("./client");
const spinner = require("./spinner");
const lark = require('@larksuiteoapi/node-sdk');
const deleteTable = async (app_token, table_id, records) => {
const execSpinner = spinner("删除中");
try {
const options = {};
if (client.userAccessToken) {
Object.assign(options, lark.withUserAccessToken(client.userAccessToken));
}
const { data } = await client.bitable.appTableRecord.batchDelete({
path: {
app_token: app_token,
table_id: table_id,
},
data: {
records: records,
},
}, options);
execSpinner.succeed("删除成功");
return data;
} catch (e) {
execSpinner.fail("删除失败");
}
};
module.exports = deleteTable;
|
2301_79424223/GitCode
|
bitable/deleteTable.js
|
JavaScript
|
unknown
| 749
|
const client = require("./client");
const spinner = require("./spinner");
const lark = require('@larksuiteoapi/node-sdk');
const exportTable = async (app_token, table_id) => {
const execSpinner = spinner("导出中");
try {
const options = {};
if (client.userAccessToken) {
Object.assign(options, lark.withUserAccessToken(client.userAccessToken));
}
const res = await client.bitable.appTableRecord.list({
params: {
page_size: 500,
},
path: {
app_token: app_token,
table_id: table_id,
},
}, options);
execSpinner.succeed("导出成功");
return res;
} catch (e) {
execSpinner.fail("导出失败");
}
};
module.exports = exportTable;
|
2301_79424223/GitCode
|
bitable/exportTable.js
|
JavaScript
|
unknown
| 727
|
const inquirer = require("inquirer");
const createTable = require("./createTable");
const addTable = require("./addTable");
const addTableRecord = require("./addTableRecord");
const deleteTable = require("./deleteTable");
const exportTable = require("./exportTable");
const { pushSummarizationToBitable } = require("./pushSummarization");
const mock = require("./mock.json");
const tableMock = mock?.map((item) => {
return {
fields: {
ID: item.id,
名称: item.title,
类型: item.type,
描述: item.description,
地址: item.sharing_url,
},
};
});
const getInput = async (msg, defaultMsg) => {
const { input } = await inquirer.prompt([
{
type: "input",
name: "input",
message: msg,
default: defaultMsg,
},
]);
return input;
};
(async function () {
while (true) {
const { command } = await inquirer.prompt([
{
type: "list",
name: "command",
message: "输入命令操作",
choices: [
"创建多维表格",
"添加一张表",
"添加表记录",
"删除表记录",
"导出多维表格",
"推送Summarization到飞书",
],
},
]);
// eslint-disable-next-line default-case
switch (command) {
case "创建多维表格":
await (async () => {
const name = await getInput("多维表格名:");
const res = await createTable({ name: name });
if (res) {
console.log(res);
}
})();
break;
case "添加一张表":
await (async () => {
const app_token = await getInput("appToken:");
const name = await getInput("表名:");
const res = await addTable(app_token, {
name: name,
default_view_name: name,
fields: [
{ field_name: "ID", type: 1 },
{ field_name: "名称", type: 1 },
{ field_name: "类型", type: 1 },
{ field_name: "描述", type: 1 },
{ field_name: "地址", type: 1 },
],
});
if (res) {
console.log(res);
}
})();
break;
case "添加表记录":
await (async () => {
const app_token = await getInput("appToken:");
const table_id = await getInput("table_id:");
const res = await addTableRecord(app_token, table_id, tableMock);
if (res) {
console.log(res);
}
})();
break;
case "删除表记录":
await (async () => {
const app_token = await getInput("appToken:");
const table_id = await getInput("table_id:");
const record = await getInput("输入record_id:");
const info = await deleteTable(app_token, table_id, [record]);
if (info) {
console.log(info);
}
})();
break;
case "导出多维表格":
await (async () => {
const app_token = await getInput("appToken:");
const table_id = await getInput("table_id:");
const res = await exportTable(app_token, table_id);
if (res) {
console.log(res);
}
})();
break;
case "推送Summarization到飞书":
await pushSummarizationToBitable();
break;
}
}
})();
|
2301_79424223/GitCode
|
bitable/index.js
|
JavaScript
|
unknown
| 3,417
|
const client = require("./client");
const spinner = require("./spinner");
const lark = require('@larksuiteoapi/node-sdk');
const fs = require('fs');
const path = require('path');
// 配置文件路径
const CONFIG_FILE = path.join(__dirname, 'bitable_config.json');
// 读取或创建配置文件
const readConfig = () => {
try {
if (fs.existsSync(CONFIG_FILE)) {
const data = fs.readFileSync(CONFIG_FILE, 'utf8');
return JSON.parse(data);
}
return null;
} catch (error) {
console.error('读取配置文件失败:', error.message);
return null;
}
};
// 保存配置文件
const saveConfig = (config) => {
try {
fs.writeFileSync(CONFIG_FILE, JSON.stringify(config, null, 2), 'utf8');
return true;
} catch (error) {
console.error('保存配置文件失败:', error.message);
return false;
}
};
// 读取temp_push_data.json文件
const readSummarizationFile = () => {
try {
const filePath = path.join(__dirname, '../summaries/temp_push_data.json');
const data = fs.readFileSync(filePath, 'utf8');
return JSON.parse(data);
} catch (error) {
console.error('读取temp_push_data.json文件失败:', error.message);
return null;
}
};
// 检查多维表格是否存在
const checkBitableExists = async (app_token) => {
try {
const options = {};
if (client.userAccessToken) {
Object.assign(options, lark.withUserAccessToken(client.userAccessToken));
}
const { data } = await client.bitable.app.get({
path: {
app_token: app_token,
},
}, options);
return data;
} catch (e) {
console.log('多维表格不存在或无法访问');
return null;
}
};
// 获取表格列表
const getTableList = async (app_token) => {
try {
const options = {};
if (client.userAccessToken) {
Object.assign(options, lark.withUserAccessToken(client.userAccessToken));
}
const { data } = await client.bitable.appTable.list({
path: {
app_token: app_token,
},
}, options);
return data;
} catch (e) {
console.error('获取表格列表失败:', e);
return null;
}
};
// 创建多维表格
const createBitable = async (name) => {
const execSpinner = spinner("创建多维表格中");
try {
const options = {};
if (client.userAccessToken) {
Object.assign(options, lark.withUserAccessToken(client.userAccessToken));
}
const { data } = await client.bitable.app.create({
data: {
name: name,
},
}, options);
execSpinner.succeed("多维表格创建成功");
return data;
} catch (e) {
execSpinner.fail("多维表格创建失败");
console.error(e);
return null;
}
};
// 添加数据表
const addTable = async (app_token, table_name) => {
const execSpinner = spinner("添加数据表中");
try {
const options = {};
if (client.userAccessToken) {
Object.assign(options, lark.withUserAccessToken(client.userAccessToken));
}
const response = await client.bitable.appTable.create({
path: {
app_token: app_token,
},
data: {
table: {
name: table_name,
fields: [
{
field_name: "标题",
type: 1, // 多行文本
},
{
field_name: "内容摘要",
type: 1, // 多行文本
},
{
field_name: "创建时间",
type: 5, // 日期时间
},
{
field_name: "来源文件",
type: 1, // 多行文本
}
]
}
},
}, options);
execSpinner.succeed("数据表添加成功");
return response.data;
} catch (e) {
execSpinner.fail("数据表添加失败");
console.error(e);
return null;
}
};
// 添加记录到表格
const addRecord = async (app_token, table_id, title, content, source) => {
const execSpinner = spinner("添加记录中");
try {
const options = {};
if (client.userAccessToken) {
Object.assign(options, lark.withUserAccessToken(client.userAccessToken));
}
const { data } = await client.bitable.appTableRecord.batchCreate({
path: {
app_token: app_token,
table_id: table_id,
},
data: {
records: [
{
fields: {
"标题": title,
"内容摘要": content,
"创建时间": new Date().getTime(),
"来源文件": source || "未知来源"
}
}
],
},
}, options);
execSpinner.succeed("记录添加成功");
return data;
} catch (e) {
execSpinner.fail("记录添加失败");
console.error(e);
return null;
}
};
// 主函数:推送summarization到飞书多维表格
const pushSummarizationToBitable = async () => {
console.log('\n=== 开始推送Summarization到飞书多维表格 ===\n');
// 1. 读取temp_push_data.json文件
const summaryData = readSummarizationFile();
if (!summaryData) {
console.error('无法读取summarization数据,退出程序');
return;
}
console.log('读取到的数据:');
console.log('标题:', summaryData.title);
console.log('来源:', summaryData.source || '未知来源');
// 处理summary字段(可能是数组或字符串)
let summaryText = '';
if (Array.isArray(summaryData.summary)) {
summaryText = summaryData.summary.join('\n');
} else {
summaryText = summaryData.summary;
}
console.log('内容:', summaryText.substring(0, 100) + '...');
// 2. 检查是否已有配置的多维表格
let config = readConfig();
let app_token = null;
let table_id = null;
let bitableUrl = null;
if (config && config.app_token) {
console.log('\n检查现有多维表格...');
const existingBitable = await checkBitableExists(config.app_token);
if (existingBitable) {
// 优先显示配置文件中的名称,如果没有则显示API返回的名称
const displayName = config.name || existingBitable.app.name;
console.log('✅ 找到现有多维表格:', displayName);
app_token = config.app_token;
// 手动构造多维表格访问URL
bitableUrl = `https://feishu.cn/base/${app_token}`;
// 如果配置中已有table_id,直接使用
if (config.table_id) {
table_id = config.table_id;
console.log('✅ 使用配置中的数据表ID:', table_id);
} else {
// 不使用现有数据表,强制创建新表
console.log('🔄 配置中无table_id,将创建新的数据表');
}
} else {
console.log('❌ 配置的多维表格不存在或无法访问,将创建新的');
config = null;
}
}
// 3. 如果没有现有表格,创建新的多维表格
if (!app_token) {
console.log('\n创建新的多维表格...');
const bitableResult = await createBitable('AI解析结果汇总');
if (!bitableResult) {
console.error('创建多维表格失败,退出程序');
return;
}
app_token = bitableResult.app.app_token;
// 手动构造多维表格访问URL
bitableUrl = `https://feishu.cn/base/${app_token}`;
console.log('\n多维表格创建成功!');
console.log('App Token:', app_token);
console.log('访问链接:', bitableUrl);
// 保存配置
const newConfig = {
app_token: app_token,
created_at: new Date().toISOString(),
name: 'AI解析结果汇总'
};
saveConfig(newConfig);
console.log('✅ 配置已保存');
}
// 4. 如果没有现有数据表,添加数据表
if (!table_id) {
console.log('\n添加数据表...');
// 生成带时间戳的唯一表名
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const uniqueTableName = `Summarization记录_${timestamp}`;
const tableResult = await addTable(app_token, uniqueTableName);
if (!tableResult || !tableResult.table_id) {
console.error('添加数据表失败,退出程序');
return;
}
table_id = tableResult.table_id;
console.log('\n数据表创建成功!');
console.log('Table ID:', table_id);
// 更新配置
const updatedConfig = readConfig();
if (updatedConfig) {
updatedConfig.table_id = table_id;
saveConfig(updatedConfig);
}
}
// 5. 添加记录
const recordResult = await addRecord(app_token, table_id, summaryData.title, summaryText, summaryData.source);
if (!recordResult) {
console.error('添加记录失败');
return;
}
console.log('\n=== 推送完成 ===');
console.log('记录ID:', recordResult.records[0].record_id);
console.log('\n请访问以下链接查看结果:');
console.log(bitableUrl);
return {
success: true,
app_token: app_token,
table_id: table_id,
record_id: recordResult.records[0].record_id,
url: bitableUrl
};
};
module.exports = {
pushSummarizationToBitable,
readSummarizationFile,
createBitable,
addTable,
addRecord,
readConfig,
saveConfig,
checkBitableExists,
getTableList
};
|
2301_79424223/GitCode
|
bitable/pushSummarization.js
|
JavaScript
|
unknown
| 9,182
|