Opera8 commited on
Commit
2a58068
·
verified ·
1 Parent(s): 32502ca

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +32 -69
app.py CHANGED
@@ -1,96 +1,59 @@
1
  import os
2
- from fastapi import FastAPI, Request, HTTPException
 
3
  from fastapi.responses import HTMLResponse, JSONResponse
4
- from fastapi.staticfiles import StaticFiles
5
  from pydantic import BaseModel
6
  import google.generativeai as genai
7
  from dotenv import load_dotenv
8
 
9
- # بارگذاری متغیرهای محیطی
10
  load_dotenv()
11
 
12
- # تنظیم API Key
13
  api_key = os.getenv("GEMINI_API_KEY")
14
 
15
- # ساخت اپلیکیشن FastAPI
16
  app = FastAPI()
17
 
18
- # مدل داده‌ای که از سمت HTML دریافت می‌شود
19
- class UserRequest(BaseModel):
20
- description: str
21
 
22
- # تنظیمات جمینای
23
  if api_key:
24
  genai.configure(api_key=api_key)
25
- generation_config = {
26
- "temperature": 0.7,
27
- "top_p": 0.95,
28
- "top_k": 40,
29
- "max_output_tokens": 8192,
30
- }
31
- model = genai.GenerativeModel(
32
- model_name="gemini-2.5-flash",
33
- generation_config=generation_config,
34
- )
35
 
36
- # 1. مسیر اصلی که فایل HTML را نمایش می‌دهد
37
  @app.get("/", response_class=HTMLResponse)
38
  async def read_root():
39
- try:
40
- with open("index.html", "r", encoding="utf-8") as f:
41
- return f.read()
42
- except FileNotFoundError:
43
- return "<h1>Error: index.html not found!</h1>"
44
 
45
- # 2. مسیر API برای پردازش درخواست
46
- @app.post("/api/generate")
47
- async def generate_lyrics(request: UserRequest):
48
  if not api_key:
49
- raise HTTPException(status_code=500, detail="Gemini API Key not set in Space secrets.")
50
 
51
- user_input = request.description
 
 
 
52
 
53
- # پرامپت سیستم دقیقاً مشابه قبل برای اعراب‌گذاری
54
- system_instruction = """
55
- You are a professional music producer and songwriter assistant.
56
- The user will provide a description or a topic for a song.
57
-
58
- You must generate two things:
59
- 1. A detailed 'Audio Prompt' in English describing the style, instruments, mood, and bpm.
60
- 2. The 'Lyrics' for the song based on the user's topic.
61
 
62
- CRITICAL RULE FOR PERSIAN LYRICS:
63
- - If the lyrics are in PERSIAN (Farsi), you MUST apply full diacritics (Vowel signs: Fathe, Zamma, Kasra, Sukun) to EVERY SINGLE WORD.
64
- - Example: Instead of "دلم گرفت", write "دِلَم گِرِفت".
65
- - This is strictly required for the TTS model.
 
66
 
67
- OUTPUT FORMAT (Return JSON structure only inside text, no markdown code blocks):
68
- {
69
- "music_prompt": "YOUR ENGLISH PROMPT HERE",
70
- "lyrics": "YOUR LYRICS HERE"
71
- }
72
  """
73
-
74
- full_prompt = f"{system_instruction}\n\nUser Input: {user_input}\nResponse must be valid JSON."
75
-
76
  try:
77
- response = model.generate_content(full_prompt)
78
- text_response = response.text
79
-
80
- # تمیز کردن خروجی برای تبدیل به JSON (حذف احتمالی ```json)
81
- clean_text = text_response.replace("```json", "").replace("```", "").strip()
82
-
83
- # تلاش برای پارس کردن جیسون، اگر جمینای متن خالی فرستاد مدیریت شود
84
- import json
85
- try:
86
- data = json.loads(clean_text)
87
- return JSONResponse(content=data)
88
- except json.JSONDecodeError:
89
- # اگر فرمت جیسون نبود، متن خام را برمی‌گردانیم
90
- return JSONResponse(content={
91
- "music_prompt": "Error parsing JSON from AI",
92
- "lyrics": clean_text
93
- })
94
-
95
  except Exception as e:
96
- raise HTTPException(status_code=500, detail=str(e))
 
1
  import os
2
+ import json
3
+ from fastapi import FastAPI, HTTPException
4
  from fastapi.responses import HTMLResponse, JSONResponse
 
5
  from pydantic import BaseModel
6
  import google.generativeai as genai
7
  from dotenv import load_dotenv
8
 
 
9
  load_dotenv()
10
 
11
+ # دریافت کلید از تنظیمات اسپیس
12
  api_key = os.getenv("GEMINI_API_KEY")
13
 
 
14
  app = FastAPI()
15
 
16
+ class IdeaRequest(BaseModel):
17
+ idea: str
 
18
 
 
19
  if api_key:
20
  genai.configure(api_key=api_key)
21
+ model = genai.GenerativeModel('gemini-2.5-flash')
 
 
 
 
 
 
 
 
 
22
 
 
23
  @app.get("/", response_class=HTMLResponse)
24
  async def read_root():
25
+ with open("index.html", "r", encoding="utf-8") as f:
26
+ return f.read()
 
 
 
27
 
28
+ @app.post("/api/refine")
29
+ async def refine_text(request: IdeaRequest):
 
30
  if not api_key:
31
+ raise HTTPException(status_code=500, detail="کلید API جمینای تنظیم نشده است.")
32
 
33
+ prompt = f"""
34
+ You are an expert music producer AI. Convert the user's description into two parts:
35
+ 1. A detailed English Audio Prompt (style, bpm, instruments, mood).
36
+ 2. Lyrics based on the topic.
37
 
38
+ CRITICAL RULE FOR LYRICS:
39
+ - If the user wants Persian/Farsi lyrics, you MUST apply FULL DIACRITICS (Fathe, Kasra, Zamma, Sukun) to EVERY single word.
40
+ - Example: write "دِلَم گِرِفت" instead of "دلم گرفت". This is vital for the TTS engine.
41
+ - If the user provides lyrics, just add diacritics to them.
 
 
 
 
42
 
43
+ Output strictly in JSON format:
44
+ {{
45
+ "music_prompt": "string",
46
+ "lyrics": "string"
47
+ }}
48
 
49
+ User Input: {request.idea}
 
 
 
 
50
  """
51
+
 
 
52
  try:
53
+ result = model.generate_content(prompt)
54
+ # تمیزکاری جیسون
55
+ clean_json = result.text.replace("```json", "").replace("```", "").strip()
56
+ data = json.loads(clean_json)
57
+ return JSONResponse(content=data)
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  except Exception as e:
59
+ return JSONResponse(content={"error": str(e)}, status_code=500)