Opera8 commited on
Commit
1ee66d8
·
verified ·
1 Parent(s): f522a40

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -88
app.py CHANGED
@@ -1,28 +1,11 @@
1
  import os
2
  import json
3
- import random
4
- from fastapi import FastAPI, HTTPException
5
  from fastapi.responses import HTMLResponse, JSONResponse
6
  from pydantic import BaseModel
7
- import google.generativeai as genai
8
- from dotenv import load_dotenv
9
-
10
- load_dotenv()
11
 
12
  app = FastAPI()
13
 
14
- # بارگذاری و پردازش کلیدها از متغیر محیطی
15
- # کلیدها باید با کاما (,) جدا شده باشند
16
- all_keys_str = os.getenv("ALL_GEMINI_API_KEYS", "")
17
- # حذف فاصله‌های اضافی و جدا کردن کلیدها
18
- GEMINI_KEYS = [k.strip() for k in all_keys_str.split(",") if k.strip()]
19
-
20
- # نمایش پیام در لاگ هنگام شروع برنامه
21
- if GEMINI_KEYS:
22
- print(f"تعداد {len(GEMINI_KEYS)} کلید جیمینای شناسایی شد")
23
- else:
24
- print("هیچ کلید جیمینای شناسایی نشد. لطفاً متغیر ALL_GEMINI_API_KEYS را تنظیم کنید.")
25
-
26
  class IdeaRequest(BaseModel):
27
  idea: str
28
 
@@ -36,74 +19,27 @@ async def read_root():
36
 
37
  @app.post("/api/refine")
38
  async def refine_text(request: IdeaRequest):
39
- if not GEMINI_KEYS:
40
- raise HTTPException(status_code=500, detail="هیچ کلید API تنظیم نشده است.")
41
-
42
- # ساخت یک لیست کپی و مخلوط کردن آن برای انتخاب تصادفی
43
- shuffled_keys = list(GEMINI_KEYS)
44
- random.shuffle(shuffled_keys)
45
-
46
- last_error = None
47
 
48
- # حلقه برای امتحان کردن کلیدها یکی پس از دیگری
49
- for api_key in shuffled_keys:
50
- try:
51
- # تنظیم کلید برای این تلاش
52
- genai.configure(api_key=api_key)
53
-
54
- # استفاده از مدل
55
- model = genai.GenerativeModel('gemini-2.5-flash')
56
-
57
- # پرامپت دقیق برای تشخیص زبان و جلوگیری از توضیحات اضافی
58
- prompt = f"""
59
- You are a professional songwriter and music producer.
60
- Task: Convert the user's input into a COMPLETE song structure and a music generation prompt.
61
-
62
- 1. **Music Prompt (English):** Describe the mood, instruments, BPM, and style suitable for an AI music generator.
63
-
64
- 2. **Lyrics (Match User's Language):**
65
- - **Language Detection:** Detect the language of the "User Input" (e.g., English, Persian, Spanish, etc.).
66
- - **Write the lyrics entirely in that detected language.**
67
- - The song MUST be long enough for **3 to 5 minutes**.
68
- - If the language is Persian/Arabic, do **NOT** use diacritics (اعراب نگذار).
69
- - You MUST use the following structure tags exactly:
70
- [Verse 1]
71
- [Pre-Chorus]
72
- [Chorus]
73
- [Verse 2]
74
- [Chorus]
75
- [Bridge]
76
- [Chorus]
77
- [Outro]
78
-
79
- **CRITICAL RULES FOR LYRICS content:**
80
- - The "lyrics" field must contain **ONLY the words to be sung**.
81
- - **ABSOLUTELY NO** descriptive text, stage directions, or instrumental notes inside the lyrics (e.g., DO NOT write "(Instrumental)", "(Fade out)", "(Repeat 2x)", or descriptions of the solo).
82
- - For instrumental sections, if there are no words to sing, leave the content under that tag empty or just write the tag itself.
83
- - Do NOT write things like "Guitar solo starts here" inside the lyrics value.
84
-
85
- Output strictly in JSON format:
86
- {{
87
- "music_prompt": "YOUR ENGLISH PROMPT HERE",
88
- "lyrics": "YOUR FULL LYRICS HERE (ONLY SUNG WORDS IN DETECTED LANGUAGE)"
89
- }}
90
-
91
- User Input: {request.idea}
92
- """
93
-
94
- # تلاش برای تولید محتوا
95
- result = model.generate_content(prompt)
96
- clean_json = result.text.replace("```json", "").replace("```", "").strip()
97
- data = json.loads(clean_json)
98
-
99
- # اگر موفقیت‌آمیز بود، خروجی را برگردان و از حلقه خارج شو
100
- return JSONResponse(content=data)
101
-
102
- except Exception as e:
103
- # اگر کلید فعلی خطا داد (مثلاً اعتبار تمام شده)، لاگ کن و برو سراغ کلید بعدی
104
- print(f"Error with a key: {e}. Trying next key...")
105
- last_error = e
106
- continue
107
-
108
- # اگر تمام کلیدها تست شدند و همه خطا دادند
109
- return JSONResponse(content={"error": f"All keys failed. Last error: {str(last_error)}"}, status_code=500)
 
1
  import os
2
  import json
3
+ from fastapi import FastAPI
 
4
  from fastapi.responses import HTMLResponse, JSONResponse
5
  from pydantic import BaseModel
 
 
 
 
6
 
7
  app = FastAPI()
8
 
 
 
 
 
 
 
 
 
 
 
 
 
9
  class IdeaRequest(BaseModel):
10
  idea: str
11
 
 
19
 
20
  @app.post("/api/refine")
21
  async def refine_text(request: IdeaRequest):
22
+ # چون جیمینای نداریم، فرض می‌کنیم ورودی کاربر همان متن آهنگ است
23
+ user_input = request.idea.strip()
 
 
 
 
 
 
24
 
25
+ # تشخیص ساده برای اینکه آیا ورودی فارسی است یا انگلیسی (برای جهت متن)
26
+ is_persian = any("\u0600" <= c <= "\u06FF" for c in user_input)
27
+
28
+ # ساختاردهی دستی (چون هوش مصنوعی نداریم که ورس و کورس بسازد)
29
+ # کل متن کاربر را در یک بخش [Verse] قرار می‌دهیم
30
+ lyrics = f"""[Verse]
31
+ {user_input}
32
+ """
33
+
34
+ # پرامپت موسیقی پیش‌فرض (چون نمی‌توانیم سبک را از متن استخراج کنیم)
35
+ # اگر متن فارسی بود، سبک پاپ ایرانی در نظر می‌گیریم
36
+ if is_persian:
37
+ music_prompt = "Persian Pop song, emotional, clear vocals, high quality, 120 bpm"
38
+ else:
39
+ music_prompt = "Pop song, catchy melody, clear vocals, high quality, 120 bpm"
40
+
41
+ # خروجی استاندارد که فرانت‌اند انتظار دارد
42
+ return JSONResponse(content={
43
+ "music_prompt": music_prompt,
44
+ "lyrics": lyrics
45
+ })