Skip to content
项目
群组
代码片段
帮助
当前项目
正在载入...
登录 / 注册
切换导航面板
S
studyweb
项目
项目
详情
活动
周期分析
仓库
仓库
文件
提交
分支
标签
贡献者
图表
比较
统计图
议题
0
议题
0
列表
看板
标记
里程碑
合并请求
0
合并请求
0
CI / CD
CI / CD
流水线
作业
日程
统计图
Wiki
Wiki
代码片段
代码片段
成员
成员
折叠边栏
关闭边栏
活动
图像
聊天
创建新问题
作业
提交
问题看板
Open sidebar
project
studyweb
Commits
58c1d2b9
提交
58c1d2b9
authored
7月 17, 2026
作者:
caifuming
浏览文件
操作
浏览文件
下载
电子邮件补丁
差异文件
ljy_完善项目模块
上级
2f089360
全部展开
隐藏空白字符变更
内嵌
并排
正在显示
26 个修改的文件
包含
619 行增加
和
141 行删除
+619
-141
README.md
ai-service/README.md
+1
-2
auth.py
ai-service/app/ai_calling/auth.py
+7
-4
ai_chat.py
ai-service/app/api/ai_chat.py
+12
-3
health.py
ai-service/app/api/health.py
+23
-2
project.py
ai-service/app/api/project.py
+0
-0
main.py
ai-service/app/main.py
+3
-2
project_catalog.py
ai-service/app/project_catalog.py
+115
-0
project_recommend_response.schema.json
...app/prompt/schemas/project_recommend_response.schema.json
+31
-0
project_recommend_v1.yaml
ai-service/app/prompt/templates/project_recommend_v1.yaml
+20
-0
test_ai_calling.py
ai-service/tests/test_ai_calling.py
+0
-0
test_project_endpoints.py
ai-service/tests/test_project_endpoints.py
+156
-0
ProjectFileController.java
...orm/backend/project/controller/ProjectFileController.java
+40
-1
ProjectAiClientService.java
...tform/backend/project/service/ProjectAiClientService.java
+14
-4
ProjectFileService.java
.../platform/backend/project/service/ProjectFileService.java
+34
-3
ProjectPermissionService.java
...orm/backend/project/service/ProjectPermissionService.java
+16
-0
ProjectService.java
.../com/platform/backend/project/service/ProjectService.java
+2
-4
MinioStorageService.java
...platform/backend/project/storage/MinioStorageService.java
+37
-0
ProjectFileServiceTest.java
...tform/backend/project/service/ProjectFileServiceTest.java
+30
-6
package.json
frontend/package.json
+5
-3
pnpm-lock.yaml
frontend/pnpm-lock.yaml
+0
-0
App.tsx
frontend/src/App.tsx
+8
-6
ProjectPage.tsx
frontend/src/pages/ProjectPage.tsx
+0
-0
permissionApi.ts
frontend/src/services/permissionApi.ts
+1
-0
useAuthStore.ts
frontend/src/stores/useAuthStore.ts
+19
-101
import_data.py
milvus-lab/scripts/import_data.py
+45
-0
start.sh
scripts/start.sh
+0
-0
没有找到文件。
ai-service/README.md
浏览文件 @
58c1d2b9
...
...
@@ -17,4 +17,4 @@ python -m app.main
## 端口
默认 7083,供 backend-app 反向代理调用。
\ No newline at end of file
默认 7083,供 backend-app 反向代理调用。
ai-service/app/ai_calling/auth.py
浏览文件 @
58c1d2b9
...
...
@@ -3,19 +3,22 @@ from __future__ import annotations
import
os
import
secrets
from
typing
import
Annotated
from
fastapi
import
H
TTPException
,
Request
,
status
from
fastapi
import
H
eader
,
HTTPException
,
status
def
_get_expected_internal_token
()
->
str
:
return
os
.
getenv
(
"AI_INTERNAL_TOKEN"
,
"dev-internal-token"
)
def
require_internal_token
(
request
:
Request
,
async
def
require_internal_token
(
x_internal_token
:
Annotated
[
str
|
None
,
Header
(
alias
=
"X-Internal-Token"
),
]
=
None
,
)
->
None
:
expected_token
=
_get_expected_internal_token
()
x_internal_token
=
request
.
headers
.
get
(
"X-Internal-Token"
)
if
not
x_internal_token
or
not
secrets
.
compare_digest
(
x_internal_token
,
expected_token
):
raise
HTTPException
(
status_code
=
status
.
HTTP_401_UNAUTHORIZED
,
...
...
ai-service/app/api/ai_chat.py
浏览文件 @
58c1d2b9
"""AI chat API routes."""
from
fastapi
import
APIRouter
,
Depends
from
fastapi.responses
import
JSONResponse
from
app.ai_calling.auth
import
require_internal_token
from
app.ai_calling.schemas
import
AIChatRequest
,
AIChatResponse
,
AIHealthResponse
...
...
@@ -15,8 +16,16 @@ async def chat(req: AIChatRequest) -> AIChatResponse:
return
await
service
.
chat
(
req
)
@router.get
(
"/health"
,
response_model
=
AIHealthResponse
,
dependencies
=
[
Depends
(
require_internal_token
)])
async
def
ai_health
()
->
AIHealthResponse
:
@router.get
(
"/health"
,
response_model
=
AIHealthResponse
,
dependencies
=
[
Depends
(
require_internal_token
)],
responses
=
{
503
:
{
"model"
:
AIHealthResponse
}},
)
async
def
ai_health
():
"""Return AI-calling specific health status without changing legacy health output."""
service
=
get_ai_service
()
return
service
.
get_health_status
()
health
=
service
.
get_health_status
()
if
health
.
unhealthy
:
return
JSONResponse
(
status_code
=
503
,
content
=
health
.
model_dump
())
return
health
ai-service/app/api/health.py
浏览文件 @
58c1d2b9
"""健康检查路由。"""
from
fastapi
import
APIRouter
from
fastapi.responses
import
JSONResponse
from
app.ai_calling.service
import
get_ai_service
router
=
APIRouter
()
@router.get
(
""
)
async
def
health
()
->
dict
:
return
{
"status"
:
"ok"
,
"service"
:
"ai-service"
,
"version"
:
"1.0.0"
}
\ No newline at end of file
return
{
"status"
:
"ok"
,
"service"
:
"ai-service"
,
"version"
:
"1.0.0"
}
@router.get
(
"/readiness"
,
responses
=
{
503
:
{
"description"
:
"AI calling layer is unhealthy."
}},
)
async
def
readiness
():
"""Return 503 when the AI calling layer has crossed its failure threshold."""
ai_health
=
get_ai_service
()
.
get_health_status
()
payload
=
{
"status"
:
"unhealthy"
if
ai_health
.
unhealthy
else
"ok"
,
"service"
:
"ai-service"
,
"checks"
:
{
"ai_calling"
:
ai_health
.
status
,
},
}
if
ai_health
.
unhealthy
:
return
JSONResponse
(
status_code
=
503
,
content
=
payload
)
return
payload
ai-service/app/api/project.py
浏览文件 @
58c1d2b9
差异被折叠。
点击展开。
ai-service/app/main.py
浏览文件 @
58c1d2b9
...
...
@@ -16,11 +16,12 @@ app.add_middleware(
allow_headers
=
[
"*"
],
)
from
app.api
import
ai
,
health
,
knowledge
# noqa: E402
from
app.api
import
ai
_chat
,
health
,
knowledge
,
project
# noqa: E402
app
.
include_router
(
health
.
router
,
prefix
=
"/api/health"
,
tags
=
[
"health"
])
app
.
include_router
(
knowledge
.
router
,
prefix
=
"/api/knowledge"
,
tags
=
[
"knowledge"
])
app
.
include_router
(
ai
.
router
,
prefix
=
"/api/v1/ai"
,
tags
=
[
"ai"
])
app
.
include_router
(
ai_chat
.
router
,
prefix
=
"/api/v1/ai"
,
tags
=
[
"ai"
])
app
.
include_router
(
project
.
router
,
prefix
=
"/ai"
,
tags
=
[
"project-ai"
])
if
__name__
==
"__main__"
:
...
...
ai-service/app/project_catalog.py
0 → 100644
浏览文件 @
58c1d2b9
"""Read-only access to locally collected GitHub repository knowledge."""
from
__future__
import
annotations
import
hashlib
import
json
from
pathlib
import
Path
from
typing
import
Any
PROJECT_ROOT
=
Path
(
__file__
)
.
resolve
()
.
parents
[
2
]
GITHUB_DATA_DIR
=
PROJECT_ROOT
/
"shared"
/
"data"
/
"github_repos"
KNOWLEDGE_OUTPUTS_DIR
=
GITHUB_DATA_DIR
/
"knowledge_outputs"
NORMALIZED_DIR
=
GITHUB_DATA_DIR
/
"normalized"
def
load_github_candidates
()
->
list
[
dict
[
str
,
Any
]]:
"""Convert collected knowledge records into recommendation candidates."""
candidates
:
list
[
dict
[
str
,
Any
]]
=
[]
for
path
in
_json_files
(
KNOWLEDGE_OUTPUTS_DIR
):
knowledge
=
_load_json
(
path
)
if
not
knowledge
:
continue
normalized
=
_load_json
(
NORMALIZED_DIR
/
path
.
name
)
or
{}
repo_url
=
str
(
knowledge
.
get
(
"repo_url"
)
or
normalized
.
get
(
"repo_url"
)
or
""
)
.
strip
()
repo_name
=
str
(
knowledge
.
get
(
"repo_name"
)
or
normalized
.
get
(
"repo_name"
)
or
path
.
stem
)
.
strip
()
if
not
repo_url
or
not
repo_name
:
continue
tags
=
_clean_strings
(
knowledge
.
get
(
"tags"
))
primary_language
=
str
(
normalized
.
get
(
"primary_language"
)
or
""
)
.
strip
()
tech_stack
=
_clean_strings
([
primary_language
,
*
tags
[:
5
]])
candidates
.
append
(
{
"project_id"
:
stable_project_id
(
repo_url
),
"project_name"
:
repo_name
,
"project_type"
:
"github"
,
"description"
:
str
(
knowledge
.
get
(
"summary"
)
or
""
)
.
strip
()
or
None
,
"difficulty_level"
:
"L3"
,
"tech_stack"
:
tech_stack
,
"tags"
:
tags
,
"stars"
:
_optional_int
(
normalized
.
get
(
"stars"
)),
"github_url"
:
repo_url
,
}
)
return
candidates
def
find_github_knowledge
(
source_code_url
:
str
|
None
,
project_name
:
str
|
None
,
)
->
dict
[
str
,
Any
]
|
None
:
"""Find a collected knowledge record by GitHub URL, then by repository name."""
normalized_url
=
_normalize_repo_url
(
source_code_url
)
normalized_name
=
(
project_name
or
""
)
.
strip
()
.
casefold
()
name_match
:
dict
[
str
,
Any
]
|
None
=
None
for
path
in
_json_files
(
KNOWLEDGE_OUTPUTS_DIR
):
record
=
_load_json
(
path
)
if
not
record
:
continue
repo_url
=
_normalize_repo_url
(
str
(
record
.
get
(
"repo_url"
)
or
""
))
if
normalized_url
and
repo_url
==
normalized_url
:
return
record
repo_name
=
str
(
record
.
get
(
"repo_name"
)
or
""
)
.
strip
()
.
casefold
()
if
normalized_name
and
repo_name
==
normalized_name
:
name_match
=
record
return
name_match
def
stable_project_id
(
repo_url
:
str
)
->
int
:
"""Build a stable positive ID for standalone local-catalog responses."""
digest
=
hashlib
.
sha256
(
_normalize_repo_url
(
repo_url
)
.
encode
(
"utf-8"
))
.
digest
()
return
int
.
from_bytes
(
digest
[:
8
],
"big"
)
%
2
_000_000_000
+
1
def
_json_files
(
directory
:
Path
)
->
list
[
Path
]:
if
not
directory
.
is_dir
():
return
[]
return
sorted
(
path
for
path
in
directory
.
glob
(
"*.json"
)
if
path
.
is_file
())
def
_load_json
(
path
:
Path
)
->
dict
[
str
,
Any
]
|
None
:
try
:
payload
=
json
.
loads
(
path
.
read_text
(
encoding
=
"utf-8"
))
except
(
OSError
,
json
.
JSONDecodeError
):
return
None
return
payload
if
isinstance
(
payload
,
dict
)
else
None
def
_normalize_repo_url
(
value
:
str
|
None
)
->
str
:
url
=
(
value
or
""
)
.
strip
()
.
rstrip
(
"/"
)
if
url
.
endswith
(
".git"
):
url
=
url
[:
-
4
]
return
url
.
casefold
()
def
_clean_strings
(
values
:
Any
)
->
list
[
str
]:
if
not
isinstance
(
values
,
list
):
return
[]
cleaned
:
list
[
str
]
=
[]
seen
:
set
[
str
]
=
set
()
for
value
in
values
:
item
=
str
(
value
or
""
)
.
strip
()
key
=
item
.
casefold
()
if
item
and
key
not
in
seen
:
seen
.
add
(
key
)
cleaned
.
append
(
item
)
return
cleaned
def
_optional_int
(
value
:
Any
)
->
int
|
None
:
try
:
return
int
(
value
)
if
value
is
not
None
else
None
except
(
TypeError
,
ValueError
):
return
None
ai-service/app/prompt/schemas/project_recommend_response.schema.json
0 → 100644
浏览文件 @
58c1d2b9
{
"$schema"
:
"https://json-schema.org/draft/2020-12/schema"
,
"type"
:
"object"
,
"additionalProperties"
:
false
,
"required"
:
[
"recommendations"
],
"properties"
:
{
"recommendations"
:
{
"type"
:
"array"
,
"items"
:
{
"type"
:
"object"
,
"additionalProperties"
:
false
,
"required"
:
[
"project_id"
,
"match_reason"
],
"properties"
:
{
"project_id"
:
{
"type"
:
"integer"
},
"match_reason"
:
{
"type"
:
"string"
,
"minLength"
:
50
,
"maxLength"
:
200
}
}
}
}
}
}
ai-service/app/prompt/templates/project_recommend_v1.yaml
0 → 100644
浏览文件 @
58c1d2b9
name
:
project_recommend_v1
version
:
v1
response_schema
:
project_recommend_response.schema.json
required_variables
:
-
seed_project_json
-
candidates_json
system
:
|
You generate recommendation reasons for an intern training platform.
Return strict JSON only. Do not add candidates or change project IDs.
Each match_reason must be 50 to 200 Chinese characters and must explain
concrete overlap, learning value, and one practical review suggestion.
user
:
|
Seed project JSON:
{seed_project_json}
<CANDIDATES_JSON>
{candidates_json}
</CANDIDATES_JSON>
Return one match_reason for every candidate project_id.
ai-service/tests/test_ai_calling.py
0 → 100644
浏览文件 @
58c1d2b9
差异被折叠。
点击展开。
ai-service/tests/test_project_endpoints.py
0 → 100644
浏览文件 @
58c1d2b9
from
__future__
import
annotations
import
asyncio
import
os
import
unittest
from
app.ai_calling.service
import
get_ai_service
from
app.api.project
import
(
KnowledgeExtractRequest
,
RecommendCandidate
,
RecommendRequest
,
RecommendSeedProject
,
extract_knowledge
,
recommend_projects
,
)
from
app.project_catalog
import
find_github_knowledge
,
load_github_candidates
class
ProjectEndpointTests
(
unittest
.
TestCase
):
def
setUp
(
self
)
->
None
:
self
.
previous_provider
=
os
.
environ
.
get
(
"AI_DEFAULT_PROVIDER"
)
self
.
previous_model
=
os
.
environ
.
get
(
"AI_DEFAULT_MODEL"
)
os
.
environ
[
"AI_DEFAULT_PROVIDER"
]
=
"mock"
os
.
environ
[
"AI_DEFAULT_MODEL"
]
=
"mock-model"
get_ai_service
.
cache_clear
()
def
tearDown
(
self
)
->
None
:
if
self
.
previous_provider
is
None
:
os
.
environ
.
pop
(
"AI_DEFAULT_PROVIDER"
,
None
)
else
:
os
.
environ
[
"AI_DEFAULT_PROVIDER"
]
=
self
.
previous_provider
if
self
.
previous_model
is
None
:
os
.
environ
.
pop
(
"AI_DEFAULT_MODEL"
,
None
)
else
:
os
.
environ
[
"AI_DEFAULT_MODEL"
]
=
self
.
previous_model
get_ai_service
.
cache_clear
()
def
test_local_catalog_is_available
(
self
)
->
None
:
candidates
=
load_github_candidates
()
self
.
assertGreaterEqual
(
len
(
candidates
),
10
)
self
.
assertIsNotNone
(
find_github_knowledge
(
"https://github.com/langchain-ai/langchain"
,
None
))
def
test_recommend_uses_local_catalog_when_candidates_are_missing
(
self
)
->
None
:
request
=
RecommendRequest
(
project_type
=
"github"
,
seed_project
=
RecommendSeedProject
(
id
=
1
,
name
=
"RAG 学习项目"
,
difficulty_level
=
"L3"
,
tech_stack
=
[
"Python"
],
tags
=
[
"RAG"
,
"LLM"
],
),
limit
=
3
,
)
response
=
asyncio
.
run
(
recommend_projects
(
request
))
self
.
assertTrue
(
response
.
success
)
self
.
assertEqual
(
response
.
data
.
source
,
"ai"
)
self
.
assertEqual
(
len
(
response
.
data
.
recommendations
),
3
)
self
.
assertTrue
(
all
(
0
<=
item
.
match_score
<=
1
for
item
in
response
.
data
.
recommendations
))
self
.
assertTrue
(
all
(
50
<=
len
(
item
.
match_reason
)
<=
200
for
item
in
response
.
data
.
recommendations
))
def
test_recommend_preserves_supplied_candidate_contract
(
self
)
->
None
:
request
=
RecommendRequest
(
project_type
=
"github"
,
seed_project
=
RecommendSeedProject
(
id
=
1
,
name
=
"FastAPI 服务"
,
difficulty_level
=
"L3"
,
tech_stack
=
[
"Python"
,
"FastAPI"
],
tags
=
[
"API"
],
),
candidates
=
[
RecommendCandidate
(
project_id
=
99
,
project_name
=
"fastapi"
,
project_type
=
"github"
,
difficulty_level
=
"L3"
,
tech_stack
=
[
"Python"
,
"FastAPI"
],
tags
=
[
"API"
],
github_url
=
"https://github.com/fastapi/fastapi"
,
)
],
)
response
=
asyncio
.
run
(
recommend_projects
(
request
))
self
.
assertEqual
(
response
.
data
.
recommendations
[
0
]
.
project_id
,
99
)
self
.
assertEqual
(
response
.
data
.
recommendations
[
0
]
.
github_url
,
"https://github.com/fastapi/fastapi"
)
def
test_recommend_falls_back_when_provider_is_unavailable
(
self
)
->
None
:
os
.
environ
[
"AI_DEFAULT_PROVIDER"
]
=
"unavailable-provider"
get_ai_service
.
cache_clear
()
request
=
RecommendRequest
(
project_type
=
"github"
,
seed_project
=
RecommendSeedProject
(
id
=
1
,
name
=
"FastAPI 服务"
,
difficulty_level
=
"L3"
,
tech_stack
=
[
"Python"
,
"FastAPI"
],
tags
=
[
"API"
],
),
candidates
=
[
RecommendCandidate
(
project_id
=
99
,
project_name
=
"fastapi"
,
project_type
=
"github"
,
difficulty_level
=
"L3"
,
tech_stack
=
[
"Python"
,
"FastAPI"
],
tags
=
[
"API"
],
github_url
=
"https://github.com/fastapi/fastapi"
,
)
],
)
response
=
asyncio
.
run
(
recommend_projects
(
request
))
self
.
assertTrue
(
response
.
success
)
self
.
assertEqual
(
response
.
data
.
source
,
"fallback"
)
self
.
assertEqual
(
len
(
response
.
data
.
recommendations
),
1
)
self
.
assertGreaterEqual
(
len
(
response
.
data
.
recommendations
[
0
]
.
match_reason
),
50
)
def
test_knowledge_extract_uses_collected_github_record
(
self
)
->
None
:
request
=
KnowledgeExtractRequest
(
project_id
=
1
,
project_type
=
"github"
,
project_name
=
"langchain"
,
difficulty_level
=
"L3"
,
source_code_url
=
"https://github.com/langchain-ai/langchain"
,
)
response
=
asyncio
.
run
(
extract_knowledge
(
request
))
self
.
assertTrue
(
response
.
success
)
self
.
assertGreater
(
len
(
response
.
data
.
knowledge_points
),
1
)
self
.
assertNotEqual
(
response
.
data
.
knowledge_points
[
0
]
.
name
,
"项目需求理解"
)
self
.
assertEqual
(
response
.
data
.
knowledge_points
[
0
]
.
material_url
,
"https://github.com/langchain-ai/langchain"
,
)
def
test_knowledge_extract_keeps_rule_fallback_for_mock_provider
(
self
)
->
None
:
request
=
KnowledgeExtractRequest
(
project_id
=
2
,
project_type
=
"internal"
,
project_name
=
"内部 API 项目"
,
difficulty_level
=
"L2"
,
tech_stack
=
[
"FastAPI"
],
project_content
=
"Build an internal REST API with FastAPI."
,
)
response
=
asyncio
.
run
(
extract_knowledge
(
request
))
names
=
[
item
.
name
for
item
in
response
.
data
.
knowledge_points
]
self
.
assertIn
(
"项目需求理解"
,
names
)
self
.
assertIn
(
"FastAPI 实践"
,
names
)
if
__name__
==
"__main__"
:
unittest
.
main
()
backend/apps/backend-app/src/main/java/com/platform/backend/project/controller/ProjectFileController.java
浏览文件 @
58c1d2b9
...
...
@@ -6,10 +6,18 @@ import com.platform.backend.project.dto.FileDtos;
import
com.platform.backend.project.service.ProjectPermissionService
;
import
com.platform.backend.project.service.ProjectFileService
;
import
lombok.RequiredArgsConstructor
;
import
org.springframework.http.ContentDisposition
;
import
org.springframework.http.HttpHeaders
;
import
org.springframework.http.MediaType
;
import
org.springframework.http.ResponseEntity
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.web.bind.annotation.*
;
import
org.springframework.web.servlet.mvc.method.annotation.StreamingResponseBody
;
import
org.springframework.web.multipart.MultipartFile
;
import
java.nio.charset.StandardCharsets
;
import
java.util.Set
;
@RestController
@RequestMapping
(
"/api/v1/files"
)
@RequiredArgsConstructor
...
...
@@ -25,7 +33,7 @@ public class ProjectFileController {
@RequestParam
(
"file_type"
)
String
fileType
,
Authentication
authentication
)
{
accessService
.
require
Role
(
authentication
,
"ADMIN
"
);
accessService
.
require
Permission
(
authentication
,
"file:upload
"
);
User
user
=
accessService
.
currentUser
(
authentication
);
return
ApiResponse
.
success
(
fileService
.
upload
(
file
,
projectId
,
projectType
,
fileType
,
user
));
}
...
...
@@ -38,4 +46,35 @@ public class ProjectFileController {
User
user
=
accessService
.
currentUser
(
authentication
);
return
ApiResponse
.
success
(
fileService
.
downloadUrl
(
fileId
,
user
));
}
/**
* 通过后端代理返回文件内容,使远程浏览器不需要直接访问 MinIO 的 localhost 地址。
*/
@GetMapping
(
"/{fileId}/content"
)
public
ResponseEntity
<
StreamingResponseBody
>
content
(
@PathVariable
Long
fileId
,
@RequestParam
(
defaultValue
=
"attachment"
)
String
disposition
,
Authentication
authentication
)
{
if
(!
Set
.
of
(
"inline"
,
"attachment"
).
contains
(
disposition
))
{
throw
new
IllegalArgumentException
(
"disposition 仅支持 inline 或 attachment"
);
}
User
user
=
accessService
.
currentUser
(
authentication
);
ProjectFileService
.
FileContent
content
=
fileService
.
prepareContent
(
fileId
,
user
);
ContentDisposition
contentDisposition
=
ContentDisposition
.
builder
(
disposition
)
.
filename
(
content
.
fileName
(),
StandardCharsets
.
UTF_8
)
.
build
();
MediaType
mediaType
;
try
{
mediaType
=
MediaType
.
parseMediaType
(
content
.
contentType
());
}
catch
(
IllegalArgumentException
ignored
)
{
mediaType
=
MediaType
.
APPLICATION_OCTET_STREAM
;
}
StreamingResponseBody
body
=
outputStream
->
fileService
.
writeContent
(
content
,
outputStream
);
return
ResponseEntity
.
ok
()
.
contentType
(
mediaType
)
.
contentLength
(
content
.
contentLength
())
.
header
(
HttpHeaders
.
CONTENT_DISPOSITION
,
contentDisposition
.
toString
())
.
body
(
body
);
}
}
backend/apps/backend-app/src/main/java/com/platform/backend/project/service/ProjectAiClientService.java
浏览文件 @
58c1d2b9
...
...
@@ -207,6 +207,8 @@ public class ProjectAiClientService {
AiRecommendRequest
request
=
new
AiRecommendRequest
();
request
.
setProjectType
(
projectType
);
request
.
setLimit
(
limit
==
null
?
5
:
limit
);
// ai-service 的推荐接口要求数组字段必须是 list,显式传空数组避免 null 触发 422。
request
.
setExcludeIds
(
List
.
of
());
request
.
setSeedProject
(
toSeedProject
(
seedProject
));
request
.
setCandidates
(
candidates
.
stream
().
map
(
this
::
toCandidate
).
toList
());
response
=
runProtected
(
"recommend"
,
()
->
aiWebClient
.
post
()
...
...
@@ -581,8 +583,8 @@ public class ProjectAiClientService {
seed
.
setId
(
project
.
getId
());
seed
.
setName
(
project
.
getName
());
seed
.
setDifficultyLevel
(
project
.
getDifficultyLevel
());
seed
.
setTechStack
(
project
.
getTechStack
(
));
seed
.
setTags
(
project
.
getKnowledgeTags
(
));
seed
.
setTechStack
(
nonNullList
(
project
.
getTechStack
()
));
seed
.
setTags
(
nonNullList
(
project
.
getKnowledgeTags
()
));
return
seed
;
}
...
...
@@ -593,13 +595,21 @@ public class ProjectAiClientService {
aiCandidate
.
setProjectType
(
candidate
.
getProjectType
());
aiCandidate
.
setDescription
(
candidate
.
getDescription
());
aiCandidate
.
setDifficultyLevel
(
candidate
.
getDifficultyLevel
());
aiCandidate
.
setTechStack
(
candidate
.
getTechStack
(
));
aiCandidate
.
setTags
(
candidate
.
getTags
(
));
aiCandidate
.
setTechStack
(
nonNullList
(
candidate
.
getTechStack
()
));
aiCandidate
.
setTags
(
nonNullList
(
candidate
.
getTags
()
));
aiCandidate
.
setStars
(
candidate
.
getStars
());
aiCandidate
.
setGithubUrl
(
candidate
.
getGithubUrl
());
return
aiCandidate
;
}
/**
* 推荐接口对数组字段做了严格校验,这里统一把 null 归一为 [],
* 避免后端内部请求因为空集合语义不一致而返回 422。
*/
private
List
<
String
>
nonNullList
(
List
<
String
>
values
)
{
return
values
==
null
?
List
.
of
()
:
values
;
}
private
RecommendationDtos
.
RecommendationItem
toRecommendationItem
(
AiRecommendItem
item
)
{
RecommendationDtos
.
RecommendationItem
result
=
new
RecommendationDtos
.
RecommendationItem
();
result
.
setProjectId
(
item
.
getProjectId
());
...
...
backend/apps/backend-app/src/main/java/com/platform/backend/project/service/ProjectFileService.java
浏览文件 @
58c1d2b9
...
...
@@ -12,6 +12,8 @@ import org.springframework.stereotype.Service;
import
org.springframework.transaction.annotation.Transactional
;
import
org.springframework.web.multipart.MultipartFile
;
import
java.io.OutputStream
;
@Service
@RequiredArgsConstructor
public
class
ProjectFileService
{
...
...
@@ -54,13 +56,42 @@ public class ProjectFileService {
public
FileDtos
.
DownloadUrlResponse
downloadUrl
(
Long
fileId
,
User
user
)
{
ProjectAttachment
attachment
=
attachmentRepository
.
findById
(
fileId
)
.
orElseThrow
(()
->
new
ProjectBusinessException
(
"文件不存在"
));
// 仅在项目模块内按真实 role_code 判断,避免被 User.getRole() 的旧兼容实现误导。
if
(!
permissionService
.
hasRole
(
user
,
"ADMIN"
)
&&
!
user
.
getId
().
equals
(
attachment
.
getUploadedBy
()))
{
throw
new
ProjectBusinessException
(
"仅文件所有者或 ADMIN 可获取"
);
if
(!
permissionService
.
hasPermission
(
user
,
"file:download"
))
{
throw
new
ProjectBusinessException
(
"无文件下载权限"
);
}
FileDtos
.
DownloadUrlResponse
response
=
new
FileDtos
.
DownloadUrlResponse
();
response
.
setUrl
(
minioStorageService
.
signedUrl
(
attachment
.
getFileUrl
()));
response
.
setExpiresMinutes
(
30
);
return
response
;
}
/**
* 为前端预览和下载准备文件流信息。鉴权规则与既有下载接口完全一致。
*/
public
FileContent
prepareContent
(
Long
fileId
,
User
user
)
{
ProjectAttachment
attachment
=
attachmentRepository
.
findById
(
fileId
)
.
orElseThrow
(()
->
new
ProjectBusinessException
(
"文件不存在"
));
if
(!
permissionService
.
hasPermission
(
user
,
"file:download"
))
{
throw
new
ProjectBusinessException
(
"无文件下载权限"
);
}
MinioStorageService
.
ObjectMetadata
metadata
=
minioStorageService
.
objectMetadata
(
attachment
.
getFileUrl
());
return
new
FileContent
(
attachment
.
getFileName
(),
attachment
.
getFileUrl
(),
metadata
.
contentType
(),
metadata
.
contentLength
()
);
}
public
void
writeContent
(
FileContent
content
,
OutputStream
outputStream
)
{
minioStorageService
.
writeObjectTo
(
content
.
objectName
(),
outputStream
);
}
public
record
FileContent
(
String
fileName
,
String
objectName
,
String
contentType
,
long
contentLength
)
{
}
}
backend/apps/backend-app/src/main/java/com/platform/backend/project/service/ProjectPermissionService.java
浏览文件 @
58c1d2b9
...
...
@@ -5,6 +5,7 @@ import com.platform.backend.entity.User;
import
com.platform.backend.project.common.ProjectBusinessException
;
import
com.platform.backend.repository.RoleRepository
;
import
com.platform.backend.repository.UserRepository
;
import
com.platform.backend.security.PermissionService
;
import
lombok.RequiredArgsConstructor
;
import
org.springframework.security.core.Authentication
;
import
org.springframework.stereotype.Service
;
...
...
@@ -14,6 +15,7 @@ import org.springframework.stereotype.Service;
public
class
ProjectPermissionService
{
private
final
UserRepository
userRepository
;
private
final
RoleRepository
roleRepository
;
private
final
PermissionService
permissionService
;
public
User
currentUser
(
Authentication
authentication
)
{
if
(
authentication
==
null
||
authentication
.
getName
()
==
null
)
{
...
...
@@ -50,6 +52,20 @@ public class ProjectPermissionService {
return
false
;
}
/**
* 文件等可配置能力必须按真实权限码判断,不能仅根据预置角色名称写死。
*/
public
boolean
hasPermission
(
User
user
,
String
permissionCode
)
{
return
user
.
getId
()
!=
null
&&
permissionService
.
hasPermission
(
user
.
getId
(),
permissionCode
);
}
public
void
requirePermission
(
Authentication
authentication
,
String
permissionCode
)
{
User
user
=
currentUser
(
authentication
);
if
(!
hasPermission
(
user
,
permissionCode
))
{
throw
new
ProjectBusinessException
(
"无权限操作"
);
}
}
private
String
resolveRoleCode
(
User
user
)
{
Long
roleId
=
user
.
getRoleId
();
if
(
roleId
==
null
)
{
...
...
backend/apps/backend-app/src/main/java/com/platform/backend/project/service/ProjectService.java
浏览文件 @
58c1d2b9
...
...
@@ -552,13 +552,11 @@ public class ProjectService {
if
(
objectName
==
null
||
objectName
.
isBlank
())
{
return
objectName
;
}
// 详情接口只对
上传者或管理员
回填签名 URL,避免绕过下载接口的权限判断。
// 详情接口只对
拥有文件下载权限的用户
回填签名 URL,避免绕过下载接口的权限判断。
if
(
user
==
null
)
{
return
null
;
}
boolean
isOwner
=
user
.
getId
()
!=
null
&&
user
.
getId
().
equals
(
attachment
.
getUploadedBy
());
boolean
isAdmin
=
permissionService
.
hasRole
(
user
,
"ADMIN"
);
if
(!
isOwner
&&
!
isAdmin
)
{
if
(!
permissionService
.
hasPermission
(
user
,
"file:download"
))
{
return
null
;
}
try
{
...
...
backend/apps/backend-app/src/main/java/com/platform/backend/project/storage/MinioStorageService.java
浏览文件 @
58c1d2b9
...
...
@@ -8,6 +8,7 @@ import org.springframework.beans.factory.annotation.Value;
import
org.springframework.stereotype.Service
;
import
org.springframework.web.multipart.MultipartFile
;
import
java.io.OutputStream
;
import
java.util.Set
;
import
java.util.UUID
;
import
java.util.concurrent.TimeUnit
;
...
...
@@ -62,6 +63,39 @@ public class MinioStorageService {
}
}
/**
* 读取对象元数据,供后端文件流接口设置正确的响应类型和长度。
*/
public
ObjectMetadata
objectMetadata
(
String
objectName
)
{
try
{
StatObjectResponse
stat
=
minioClient
.
statObject
(
StatObjectArgs
.
builder
()
.
bucket
(
bucket
)
.
object
(
objectName
)
.
build
());
String
contentType
=
stat
.
contentType
();
if
(
contentType
==
null
||
contentType
.
isBlank
())
{
contentType
=
"application/octet-stream"
;
}
return
new
ObjectMetadata
(
contentType
,
stat
.
size
());
}
catch
(
Exception
e
)
{
throw
new
ProjectBusinessException
(
"文件元数据读取失败:"
+
e
.
getMessage
());
}
}
/**
* 由后端将 MinIO 对象写入 HTTP 响应,避免浏览器直接访问远程服务器的 localhost MinIO 地址。
*/
public
void
writeObjectTo
(
String
objectName
,
OutputStream
outputStream
)
{
try
(
GetObjectResponse
objectStream
=
minioClient
.
getObject
(
GetObjectArgs
.
builder
()
.
bucket
(
bucket
)
.
object
(
objectName
)
.
build
()))
{
objectStream
.
transferTo
(
outputStream
);
}
catch
(
Exception
e
)
{
throw
new
ProjectBusinessException
(
"文件读取失败:"
+
e
.
getMessage
());
}
}
private
void
ensureBucket
()
{
try
{
boolean
exists
=
minioClient
.
bucketExists
(
BucketExistsArgs
.
builder
().
bucket
(
bucket
).
build
());
...
...
@@ -89,4 +123,7 @@ public class MinioStorageService {
throw
new
ProjectBusinessException
(
"仅支持 PDF/Word/Excel/压缩包"
);
}
}
public
record
ObjectMetadata
(
String
contentType
,
long
contentLength
)
{
}
}
backend/apps/backend-app/src/test/java/com/platform/backend/project/service/ProjectFileServiceTest.java
浏览文件 @
58c1d2b9
...
...
@@ -43,7 +43,7 @@ class ProjectFileServiceTest {
}
@Test
void
downloadUrlAllows
AdminEvenWhenLegacyUserRoleFieldIsNotAdminText
()
{
void
downloadUrlAllows
UsersWithConfiguredFileDownloadPermission
()
{
User
user
=
new
User
();
user
.
setId
(
100L
);
user
.
setRoleId
(
1L
);
...
...
@@ -54,18 +54,18 @@ class ProjectFileServiceTest {
attachment
.
setUploadedBy
(
200L
);
when
(
attachmentRepository
.
findById
(
20L
)).
thenReturn
(
Optional
.
of
(
attachment
));
when
(
permissionService
.
has
Role
(
user
,
"ADMIN
"
)).
thenReturn
(
true
);
when
(
permissionService
.
has
Permission
(
user
,
"file:download
"
)).
thenReturn
(
true
);
when
(
minioStorageService
.
signedUrl
(
"project/github/readme.pdf"
)).
thenReturn
(
"https://signed.example/file"
);
FileDtos
.
DownloadUrlResponse
response
=
projectFileService
.
downloadUrl
(
20L
,
user
);
assertEquals
(
"https://signed.example/file"
,
response
.
getUrl
());
assertEquals
(
30
,
response
.
getExpiresMinutes
());
verify
(
permissionService
).
has
Role
(
user
,
"ADMIN
"
);
verify
(
permissionService
).
has
Permission
(
user
,
"file:download
"
);
}
@Test
void
downloadUrlRejects
NonOwnerNonAdmi
n
()
{
void
downloadUrlRejects
UsersWithoutConfiguredFileDownloadPermissio
n
()
{
User
user
=
new
User
();
user
.
setId
(
100L
);
...
...
@@ -75,13 +75,37 @@ class ProjectFileServiceTest {
attachment
.
setUploadedBy
(
200L
);
when
(
attachmentRepository
.
findById
(
21L
)).
thenReturn
(
Optional
.
of
(
attachment
));
when
(
permissionService
.
has
Role
(
user
,
"ADMIN
"
)).
thenReturn
(
false
);
when
(
permissionService
.
has
Permission
(
user
,
"file:download
"
)).
thenReturn
(
false
);
ProjectBusinessException
exception
=
assertThrows
(
ProjectBusinessException
.
class
,
()
->
projectFileService
.
downloadUrl
(
21L
,
user
)
);
assertEquals
(
"仅文件所有者或 ADMIN 可获取"
,
exception
.
getMessage
());
assertEquals
(
"无文件下载权限"
,
exception
.
getMessage
());
}
@Test
void
prepareContentUsesTheSameConfiguredPermissionAsDownloadUrl
()
{
User
user
=
new
User
();
user
.
setId
(
100L
);
ProjectAttachment
attachment
=
new
ProjectAttachment
();
attachment
.
setId
(
22L
);
attachment
.
setFileName
(
"guide.pdf"
);
attachment
.
setFileUrl
(
"projects/1/internal/guide.pdf"
);
attachment
.
setUploadedBy
(
100L
);
when
(
attachmentRepository
.
findById
(
22L
)).
thenReturn
(
Optional
.
of
(
attachment
));
when
(
permissionService
.
hasPermission
(
user
,
"file:download"
)).
thenReturn
(
true
);
when
(
minioStorageService
.
objectMetadata
(
"projects/1/internal/guide.pdf"
))
.
thenReturn
(
new
MinioStorageService
.
ObjectMetadata
(
"application/pdf"
,
128L
));
ProjectFileService
.
FileContent
content
=
projectFileService
.
prepareContent
(
22L
,
user
);
assertEquals
(
"guide.pdf"
,
content
.
fileName
());
assertEquals
(
"application/pdf"
,
content
.
contentType
());
assertEquals
(
128L
,
content
.
contentLength
());
verify
(
permissionService
).
hasPermission
(
user
,
"file:download"
);
}
}
frontend/package.json
浏览文件 @
58c1d2b9
...
...
@@ -10,12 +10,14 @@
"lint"
:
"eslint src --ext ts,tsx"
},
"dependencies"
:
{
"@ant-design/icons"
:
"^5.5.1"
,
"antd"
:
"^5.21.2"
,
"axios"
:
"^1.7.7"
,
"mammoth"
:
"^1.12.0"
,
"react"
:
"^18.3.1"
,
"react-dom"
:
"^18.3.1"
,
"react-router-dom"
:
"^6.26.2"
,
"antd"
:
"^5.21.2"
,
"@ant-design/icons"
:
"^5.5.1"
,
"axios"
:
"^1.7.7"
,
"xlsx"
:
"^0.18.5"
,
"zustand"
:
"^4.5.5"
},
"devDependencies"
:
{
...
...
frontend/pnpm-lock.yaml
浏览文件 @
58c1d2b9
差异被折叠。
点击展开。
frontend/src/App.tsx
浏览文件 @
58c1d2b9
...
...
@@ -70,14 +70,16 @@ const PublicRoute: React.FC<{ children: React.ReactNode }> = ({ children }) => {
const
MainLayout
:
React
.
FC
=
()
=>
{
const
[
collapsed
,
setCollapsed
]
=
useState
(
false
);
const
[
selectedKey
,
setSelectedKey
]
=
useState
(
'/dashboard'
);
const
{
user
,
logout
,
isLoading
,
loadPermissions
,
permissions
}
=
useAuthStore
();
const
{
user
,
logout
,
isLoading
,
loadPermissions
}
=
useAuthStore
();
const
location
=
useLocation
();
const
navigate
=
useNavigate
();
//
加载权限
//
每次应用加载都读取后端真实权限,避免持久化的旧权限掩盖管理员的新分配。
useEffect
(()
=>
{
loadPermissions
();
},
[]);
if
(
user
)
{
void
loadPermissions
(
true
);
}
},
[
user
?.
id
,
loadPermissions
]);
// 根据用户角色过滤菜单
const
visibleMenus
=
useMemo
(()
=>
{
...
...
@@ -183,8 +185,8 @@ const MainLayout: React.FC = () => {
navigate
(
e
.
key
);
};
// 等待
权限加载完成
if
(
isLoading
||
permissions
.
length
===
0
)
{
// 等待
登录加载完成(用于登录后的首次加载)
if
(
isLoading
)
{
return
(
<
div
style=
{
{
display
:
'flex'
,
justifyContent
:
'center'
,
alignItems
:
'center'
,
height
:
'100vh'
}
}
>
<
Spin
size=
"large"
tip=
"加载中..."
/>
...
...
frontend/src/pages/ProjectPage.tsx
浏览文件 @
58c1d2b9
差异被折叠。
点击展开。
frontend/src/services/permissionApi.ts
浏览文件 @
58c1d2b9
...
...
@@ -21,6 +21,7 @@ export interface User {
status
:
number
;
createdAt
:
string
;
roles
?:
string
[];
permissions
?:
string
[];
}
// 角色类型
...
...
frontend/src/stores/useAuthStore.ts
浏览文件 @
58c1d2b9
import
{
create
}
from
'zustand'
;
import
{
persist
}
from
'zustand/middleware'
;
import
{
login
as
loginApi
,
logout
as
logoutApi
,
phoneLogin
as
phoneLoginApi
,
LoginResponse
}
from
'../services/authApi'
;
import
{
userApi
,
menuApi
,
PERMISSION_CODES
,
User
}
from
'../services/permissionApi'
;
import
{
userApi
,
menuApi
}
from
'../services/permissionApi'
;
interface
AuthState
{
user
:
LoginResponse
[
'user'
]
|
null
;
...
...
@@ -11,6 +11,7 @@ interface AuthState {
refreshToken
:
string
|
null
;
isAuthenticated
:
boolean
;
isLoading
:
boolean
;
permissionsLoading
:
boolean
;
// Actions
setAuth
:
(
data
:
LoginResponse
)
=>
void
;
...
...
@@ -18,7 +19,7 @@ interface AuthState {
phoneLogin
:
(
phone
:
string
,
smsCode
:
string
)
=>
Promise
<
void
>
;
logout
:
()
=>
Promise
<
void
>
;
clearAuth
:
()
=>
void
;
loadPermissions
:
()
=>
Promise
<
void
>
;
loadPermissions
:
(
force
?:
boolean
)
=>
Promise
<
void
>
;
loadMenus
:
()
=>
Promise
<
void
>
;
}
...
...
@@ -32,6 +33,7 @@ export const useAuthStore = create<AuthState>()(
refreshToken
:
null
,
isAuthenticated
:
false
,
isLoading
:
false
,
permissionsLoading
:
false
,
setAuth
:
(
data
:
LoginResponse
)
=>
{
localStorage
.
setItem
(
'accessToken'
,
data
.
accessToken
);
...
...
@@ -41,6 +43,7 @@ export const useAuthStore = create<AuthState>()(
accessToken
:
data
.
accessToken
,
refreshToken
:
data
.
refreshToken
,
isAuthenticated
:
true
,
permissions
:
[],
});
},
...
...
@@ -89,21 +92,27 @@ export const useAuthStore = create<AuthState>()(
accessToken
:
null
,
refreshToken
:
null
,
isAuthenticated
:
false
,
permissionsLoading
:
false
,
});
},
// 加载用户权限
loadPermissions
:
async
()
=>
{
loadPermissions
:
async
(
force
=
false
)
=>
{
const
currentState
=
get
();
// 防止重复加载
if
(
currentState
.
permissionsLoading
||
(
!
force
&&
currentState
.
permissions
.
length
>
0
))
{
return
;
}
set
({
permissionsLoading
:
true
});
try
{
// 获取
用户详情,包含权限信息
// 获取
后端按角色实际配置计算出的权限,支持管理员动态调整角色权限。
const
userDetail
=
await
userApi
.
getCurrentUser
();
// 根据用户角色预设默认权限
const
roles
=
userDetail
.
roles
||
[];
const
defaultPermissions
=
getDefaultPermissionsByRoles
(
roles
);
set
({
permissions
:
defaultPermissions
});
set
({
permissions
:
userDetail
.
permissions
||
[],
permissionsLoading
:
false
});
}
catch
(
error
)
{
console
.
error
(
'加载权限失败:'
,
error
);
set
({
permissions
:
[]
});
// 即使加载失败,也设置 permissionsLoading 为 false,避免无限等待
set
({
permissions
:
[],
permissionsLoading
:
false
});
}
},
...
...
@@ -127,99 +136,8 @@ export const useAuthStore = create<AuthState>()(
accessToken
:
state
.
accessToken
,
refreshToken
:
state
.
refreshToken
,
isAuthenticated
:
state
.
isAuthenticated
,
// 注意:permissionsLoading 不需要持久化,因为它只在运行时使用
}),
}
)
);
// 根据用户角色获取默认权限
function
getDefaultPermissionsByRoles
(
roles
:
string
[]):
string
[]
{
const
allPermissions
:
string
[]
=
[];
const
roleSet
=
new
Set
(
roles
);
// ADMIN 拥有所有权限
if
(
roleSet
.
has
(
'ADMIN'
))
{
return
Object
.
values
(
PERMISSION_CODES
);
}
// 公共权限 - 所有人都有的权限
const
publicPermissions
=
[
PERMISSION_CODES
.
PROJECT_VIEW
,
PERMISSION_CODES
.
PROJECT_SIMPLE_LIST
,
PERMISSION_CODES
.
TAG_VIEW
,
PERMISSION_CODES
.
RECOMMEND_VIEW
,
PERMISSION_CODES
.
KNOWLEDGE_VIEW
,
PERMISSION_CODES
.
DEFENSE_VIEW
,
PERMISSION_CODES
.
PROFILE_VIEW
,
PERMISSION_CODES
.
DEFECT_VIEW
,
PERMISSION_CODES
.
ADVANCED_VIEW
,
PERMISSION_CODES
.
ROLE_VIEW
,
];
allPermissions
.
push
(...
publicPermissions
);
// 主管权限
if
(
roleSet
.
has
(
'SUPERVISOR'
))
{
const
supervisorPermissions
=
[
PERMISSION_CODES
.
DIFFICULTY_VIEW
,
PERMISSION_CODES
.
DIFFICULTY_CALIBRATE
,
PERMISSION_CODES
.
DIFFICULTY_AI_SCORE_VIEW
,
PERMISSION_CODES
.
TRAINING_VIEW_ALL
,
PERMISSION_CODES
.
TRAINING_VIEW_DETAIL
,
PERMISSION_CODES
.
PREVIEW_VIEW_PROGRESS
,
PERMISSION_CODES
.
DEFENSE_AUDIT
,
PERMISSION_CODES
.
DEFENSE_PENDING_LIST
,
PERMISSION_CODES
.
HISTORY_VIEW_ALL
,
PERMISSION_CODES
.
CONTAINER_MANAGE
,
PERMISSION_CODES
.
USER_VIEW_LIST
,
PERMISSION_CODES
.
USER_VIEW_DETAIL
,
PERMISSION_CODES
.
MENTOR_DASHBOARD
,
];
allPermissions
.
push
(...
supervisorPermissions
);
}
// 导师权限
if
(
roleSet
.
has
(
'MENTOR'
))
{
const
mentorPermissions
=
[
PERMISSION_CODES
.
DIFFICULTY_VIEW
,
PERMISSION_CODES
.
TRAINING_VIEW_ASSIGNED
,
PERMISSION_CODES
.
TRAINING_VIEW_DETAIL
,
PERMISSION_CODES
.
PREVIEW_VIEW_PROGRESS
,
PERMISSION_CODES
.
DEFENSE_REVIEW
,
PERMISSION_CODES
.
DEFENSE_PENDING_LIST
,
PERMISSION_CODES
.
HISTORY_VIEW_DEPARTMENT
,
PERMISSION_CODES
.
DEFECT_ADD
,
PERMISSION_CODES
.
USER_VIEW_DETAIL
,
PERMISSION_CODES
.
MENTOR_DASHBOARD
,
];
allPermissions
.
push
(...
mentorPermissions
);
}
// 学员权限
if
(
roleSet
.
has
(
'STUDENT'
))
{
const
studentPermissions
=
[
PERMISSION_CODES
.
RECOMMEND_REQUEST
,
PERMISSION_CODES
.
RECOMMEND_CHOOSE
,
PERMISSION_CODES
.
RECOMMEND_IGNORE
,
PERMISSION_CODES
.
TRAINING_CREATE
,
PERMISSION_CODES
.
TRAINING_VIEW_OWN
,
PERMISSION_CODES
.
TRAINING_UPDATE
,
PERMISSION_CODES
.
TRAINING_DELETE
,
PERMISSION_CODES
.
TRAINING_VIEW_DETAIL
,
PERMISSION_CODES
.
PREVIEW_VIEW_KNOWLEDGE
,
PERMISSION_CODES
.
PREVIEW_SUBMIT
,
PERMISSION_CODES
.
PREVIEW_TAK_QUIZ
,
PERMISSION_CODES
.
PRACTICE_SUBMIT_ARTIFACT
,
PERMISSION_CODES
.
PRACTICE_WRITE_REPORT
,
PERMISSION_CODES
.
PRACTICE_SUBMIT_REPORT
,
PERMISSION_CODES
.
DEFENSE_APPLY
,
PERMISSION_CODES
.
HISTORY_VIEW_OWN
,
PERMISSION_CODES
.
CONTAINER_USE
,
PERMISSION_CODES
.
ADVANCED_ACCEPT
,
PERMISSION_CODES
.
ADVANCED_REJECT
,
];
allPermissions
.
push
(...
studentPermissions
);
}
// 去重
return
[...
new
Set
(
allPermissions
)];
}
milvus-lab/scripts/import_data.py
0 → 100644
浏览文件 @
58c1d2b9
import
numpy
as
np
from
pymilvus
import
MilvusClient
client
=
MilvusClient
(
uri
=
'http://localhost:19530'
)
COLLECTION
=
'demo_vector_db'
DIM
=
1536
N
=
1000
# Drop & create with GPU 6 index
client
.
drop_collection
(
COLLECTION
)
client
.
create_collection
(
COLLECTION
,
dimension
=
DIM
,
primary_field
=
'id'
,
vector_field
=
'vector'
,
index_params
=
{
'index_type'
:
'GPU_IVF_FLAT'
,
'metric_type'
:
'L2'
,
'params'
:
{
'nlist'
:
128
,
'gpu_id'
:
6
}
}
)
# Insert 1000 random vectors
np
.
random
.
seed
(
42
)
data
=
[{
'id'
:
i
,
'vector'
:
np
.
random
.
rand
(
DIM
)
.
astype
(
np
.
float32
)
.
tolist
()}
for
i
in
range
(
N
)]
client
.
insert
(
COLLECTION
,
data
=
data
)
client
.
flush
(
COLLECTION
)
# Verify
stats
=
client
.
get_collection_stats
(
COLLECTION
)
print
(
f
"集合: {COLLECTION}"
)
print
(
f
"维度: {DIM}"
)
print
(
f
"向量数量: {stats.get('row_count', '?')}"
)
print
(
f
"索引: GPU_IVF_FLAT (GPU 6)"
)
# Quick search
import
time
results
=
client
.
search
(
COLLECTION
,
data
=
[
np
.
random
.
rand
(
DIM
)
.
astype
(
np
.
float32
)
.
tolist
()],
limit
=
5
,
search_params
=
{
'nprobe'
:
16
}
)
print
(
f
"检索验证: 返回 {len(results[0])} 条结果, 示例 id={[r['id'] for r in results[0]]}"
)
scripts/start.sh
浏览文件 @
58c1d2b9
差异被折叠。
点击展开。
编写
预览
Markdown
格式
0%
重试
或
添加新文件
添加附件
取消
您添加了
0
人
到此讨论。请谨慎行事。
请先完成此评论的编辑!
取消
请
注册
或者
登录
后发表评论