3v324v23 commited on
Commit
e9541ad
·
1 Parent(s): e8e4bd8

Load data directly from CSV using pandas

Browse files
Files changed (2) hide show
  1. apps/api/routers/trade.py +66 -32
  2. requirements.txt +1 -0
apps/api/routers/trade.py CHANGED
@@ -13,41 +13,75 @@ router = APIRouter()
13
  async def search_trade_records(
14
  query: TradeQueryRequest,
15
  db: AsyncSession = Depends(get_db_session)
16
- ): # 直接返回mock数据,展示效果
 
 
 
17
  from datetime import datetime
18
- mock_items = [
19
- TradeRecordResponse(
20
- record_id=f"MOCK-{i}",
21
- source_record_id=f"SRC-{i}",
22
- source_country="US" if i % 2 == 0 else "CN",
23
- trade_direction="import" if i % 2 == 0 else "export",
24
- trade_date=datetime(2023, 1, i+1),
25
- importer_name=f"进口商{i}",
26
- exporter_name=f"出口商{i}",
27
- hs_code=f"847130{i:02d}",
28
- product_name=f"电子产品 - 样品{i}",
29
- amount=10000.0 + i * 1000,
30
- currency="USD",
31
- weight=500.0 + i * 10,
32
- weight_unit="KG",
33
- origin_country="CN",
34
- destination_country="US",
35
- departure_port="上海港",
36
- arrival_port="洛杉矶港",
37
- transport_mode="SEA"
38
- )
39
- for i in range(min(query.limit, 20))
40
- ]
41
 
42
- return PaginatedResponse(
43
- total=10000,
44
- items=mock_items
45
- ) """
46
- 检索标准贸易记录
47
- 支持按国家、方向、HS、商品、企业名、起运/目的国及日期范围筛选
48
 
49
- 当有全文搜索需求(product_name/importer_name/exporter_name)时,优先使用 Elasticsearch
50
- """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51
  print(f"[DEBUG] Received query: {query}")
52
 
53
  # 判断是否需要全文搜索
 
13
  async def search_trade_records(
14
  query: TradeQueryRequest,
15
  db: AsyncSession = Depends(get_db_session)
16
+ ):
17
+ """
18
+ 检索标准贸易记录 - 直接从CSV加载数据
19
+ """
20
  from datetime import datetime
21
+ import pandas as pd
22
+ from pathlib import Path
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
+ # 加载CSV数据
25
+ csv_path = Path(__file__).parent.parent.parent.parent / "data" / "standard_trade_records_sample.csv"
26
+ df = pd.read_csv(csv_path)
 
 
 
27
 
28
+ # 应用过滤条件
29
+ filtered_df = df.copy()
30
+
31
+ if query.source_country:
32
+ filtered_df = filtered_df[filtered_df['source_country'] == query.source_country]
33
+ if query.trade_direction:
34
+ filtered_df = filtered_df[filtered_df['trade_direction'] == query.trade_direction]
35
+ if query.hs_code:
36
+ filtered_df = filtered_df[filtered_df['hs_code'].astype(str).str.startswith(str(query.hs_code))]
37
+ if query.product_name:
38
+ filtered_df = filtered_df[filtered_df['product_name'].str.contains(query.product_name, na=False, case=False)]
39
+ if query.importer_name:
40
+ filtered_df = filtered_df[filtered_df['importer_name'].str.contains(query.importer_name, na=False, case=False)]
41
+ if query.exporter_name:
42
+ filtered_df = filtered_df[filtered_df['exporter_name'].str.contains(query.exporter_name, na=False, case=False)]
43
+
44
+ total = len(filtered_df)
45
+
46
+ # 分页
47
+ offset = (query.page - 1) * query.limit
48
+ page_df = filtered_df.iloc[offset:offset + query.limit]
49
+
50
+ # 转换为响应格式
51
+ items = []
52
+ for _, row in page_df.iterrows():
53
+ # 处理日期 - 只取日期部分
54
+ trade_date_str = str(row['trade_date']).split()[0] if pd.notna(row['trade_date']) else '2023-01-01'
55
+ try:
56
+ trade_date = datetime.fromisoformat(trade_date_str)
57
+ except:
58
+ trade_date = datetime(2023, 1, 1)
59
+
60
+ items.append(TradeRecordResponse(
61
+ record_id=str(row['record_id']),
62
+ source_record_id=str(row['source_record_id']),
63
+ source_country=str(row['source_country']),
64
+ trade_direction=str(row['trade_direction']),
65
+ trade_date=trade_date,
66
+ importer_name=str(row['importer_name']) if pd.notna(row['importer_name']) else "",
67
+ exporter_name=str(row['exporter_name']) if pd.notna(row['exporter_name']) else "",
68
+ hs_code=str(row['hs_code']) if pd.notna(row['hs_code']) else None,
69
+ product_name=str(row['product_name']) if pd.notna(row['product_name']) else None,
70
+ amount=float(row['amount']) if pd.notna(row['amount']) else None,
71
+ currency=str(row['currency']) if pd.notna(row['currency']) else None,
72
+ weight=float(row['weight']) if pd.notna(row['weight']) else None,
73
+ weight_unit=str(row['weight_unit']) if pd.notna(row['weight_unit']) else None,
74
+ origin_country=str(row['origin_country']) if pd.notna(row['origin_country']) else None,
75
+ destination_country=str(row['destination_country']) if pd.notna(row['destination_country']) else None,
76
+ departure_port=str(row['departure_port']) if pd.notna(row['departure_port']) else None,
77
+ arrival_port=str(row['arrival_port']) if pd.notna(row['arrival_port']) else None,
78
+ transport_mode=str(row['transport_mode']) if pd.notna(row['transport_mode']) else None
79
+ ))
80
+
81
+ return PaginatedResponse(
82
+ total=total,
83
+ items=items
84
+ )
85
  print(f"[DEBUG] Received query: {query}")
86
 
87
  # 判断是否需要全文搜索
requirements.txt CHANGED
@@ -16,3 +16,4 @@ boto3==1.34.131
16
  loguru==0.7.2
17
  aiohttp>=3.9.5
18
  pytest==9.0.3
 
 
16
  loguru==0.7.2
17
  aiohttp>=3.9.5
18
  pytest==9.0.3
19
+ pandas>=2.0.0