use of org.python.core.PyObject in project freemarker by apache.
the class JythonRuntime method getWriter.
public Writer getWriter(final Writer out, final Map args) {
final StringBuilder buf = new StringBuilder();
final Environment env = Environment.getCurrentEnvironment();
return new Writer() {
@Override
public void write(char[] cbuf, int off, int len) {
buf.append(cbuf, off, len);
}
@Override
public void flush() throws IOException {
interpretBuffer();
out.flush();
}
@Override
public void close() {
interpretBuffer();
}
private void interpretBuffer() {
synchronized (JythonRuntime.this) {
PyObject prevOut = systemState.stdout;
try {
setOut(out);
set("env", env);
exec(buf.toString());
buf.setLength(0);
} finally {
setOut(prevOut);
}
}
}
};
}
use of org.python.core.PyObject in project DALC-team05 by nhy31.
the class RecipeController method getTest.
@RequestMapping(value = "/recipe/recipe_detail")
public ModelAndView getTest(HttpServletRequest request, RedirectAttributes redirect, Model model, @RequestParam("recipe_code") int recipe_code) {
HttpSession session = request.getSession();
Member member = (Member) session.getAttribute("loginMember");
String allergy = member.getMember_allergy();
System.out.println("알레르기" + allergy);
String[] array = allergy.split(",");
List<String> danger = new ArrayList<>();
int alle = 0;
ModelAndView mav = new ModelAndView();
recipeService.hitsCount(recipe_code);
Recipe clickRecipe = recipeService.getRecipeFromCode(recipe_code);
clickRecipe.setOrders(recipeService.getOrders(recipe_code));
List<rUse> useList = recipeService.getUses(recipe_code);
clickRecipe.setUses(useList);
for (int i = 0; i < array.length; i++) {
System.out.println(array[i]);
for (int j = 0; j < useList.size(); j++) {
if (useList.get(j).getrUse_name().equals(array[i])) {
System.out.println("알러지재료적발 " + array[i]);
danger.add(array[i]);
alle = 1;
}
}
}
System.out.println("알러지재료" + danger.toString());
mav.addObject("danger", danger.toString());
mav.addObject("alle", alle);
mav.addObject("clickRecipe", clickRecipe);
// 입력받은 recipecode -> 하윤 toString으로 변환 추가
String inputData = Integer.toString(recipe_code);
System.out.println("인풋데이터" + inputData);
interpreter = new PythonInterpreter();
// 자카드 유사도 함수
interpreter.exec("def jaccard_similarity(s1, s2):\n" + " s1 = set(s1)\n" + " s2 = set(s2)\n" + " return float(len(s1 & s2)) / float(len(s1 | s2))");
interpreter.exec("import csv");
// 파일 read
// 절대경로(본인컴퓨터에 맞춰서 변경)
interpreter.exec("f = open('/git/DALC-team05/src/main/resources/csv/recipes.csv', 'r')");
interpreter.exec("reader = csv.reader(f)");
interpreter.exec("header = next(reader)");
// recipecode로 해당 내용 찾아서 input배열로 만듦
interpreter.exec("input = list()");
interpreter.exec("i = 0");
interpreter.exec("for row in reader:\n" + "# print(row)\n" + " if row[0] == str(" + inputData + "): \n" + " input = row \n" + " break\n" + " i+=1");
interpreter.exec("#print(input)");
// PyObject o = interpreter.eval("input");
// System.out.println("input: "+o.toString());
interpreter.exec("f.close()");
// 파일 read
// 절대경로(본인컴퓨터에 맞춰서 변경)
interpreter.exec("f = open('/git/DALC-team05/src/main/resources/csv/recipes.csv', 'r')");
interpreter.exec("reader = csv.reader(f)");
interpreter.exec("header = next(reader)");
// recipe_list: recipe csv파일에 있는 레시피들에 대한 리스트
// sim_list: 각 레시피에 대한 자카드 유사도를 담은 리스트
interpreter.exec("recipe_list = list()");
interpreter.exec("sim_list = list()");
// csv파일을 한줄씩 읽은 뒤 자카드 유사도 계산 후 리스트에 저장
interpreter.exec("i = 0");
interpreter.exec("for row in reader:\n" + " recipe_list.append(row)\n" + "# print(recipe_list[i])\n" + " sim_list.append(jaccard_similarity(row, input))\n" + "# print(sim_list[i])\n" + " i+=1");
interpreter.exec("f.close()");
// 유사도 상위 5개 (본인 포함 6개) 인덱스 추출
interpreter.exec("top = sorted(range(len(sim_list)), key=lambda i: sim_list[i])[-6:]");
interpreter.exec("#print(top)");
// PyObject ob = interpreter.eval("top");
// System.out.println("상위1: "+ob.toString());
// // 본인을 제외한 유사도 상위 레시피 5개
interpreter.exec("result = []\n");
interpreter.exec("for k in top:\n" + "# print(k)\n" + "# print(recipe_list[k])\n" + " if recipe_list[k][0] != input[0]:\n" + "# print(recipe_list[k])\n" + " result.append(recipe_list[k][0])\n" + "# print(recipe_list[k][0])\n");
// obj에 들어있는 list가 추천 된 레시피코드
PyObject obj = interpreter.eval("result[:5]");
// System.out.println("result: "+obj.toString());
// recipeCode는 5가지 유사한 recipecode가 들어있는 배열
String[] recipeCode = obj.toString().split("', '");
recipeCode[0] = recipeCode[0].split("'")[1];
recipeCode[4] = recipeCode[4].split("'")[0];
List<Recipe> relatedList = new ArrayList<>();
int i = 0;
// 하윤추가 WEB띄우기
for (String code : recipeCode) {
System.out.println(code);
int realCode = Integer.parseInt(code);
relatedList.add(recipeService.getRecipeFromCode(realCode));
System.out.println("0226확인 " + relatedList.get(i).getRecipe_title());
i++;
}
mav.addObject("relatedList", relatedList);
return mav;
}
use of org.python.core.PyObject in project oxCore by GluuFederation.
the class PythonService method loadPythonScript.
@SuppressWarnings("unchecked")
private <T> T loadPythonScript(String scriptPythonType, Class<T> scriptJavaType, PyObject[] constructorArgs, PythonInterpreter interpreter) throws PythonException {
PyObject scriptPythonTypeObject = interpreter.get(scriptPythonType);
if (scriptPythonTypeObject == null) {
return null;
}
PyObject scriptPythonTypeClass;
try {
scriptPythonTypeClass = scriptPythonTypeObject.__call__(constructorArgs);
} catch (Exception ex) {
log.error("Failed to initialize python class", ex.getMessage());
throw new PythonException(String.format("Failed to initialize python class '%s'", scriptPythonType), ex);
}
Object scriptJavaClass = scriptPythonTypeClass.__tojava__(scriptJavaType);
if (!ReflectHelper.assignableFrom(scriptJavaClass.getClass(), scriptJavaType)) {
return null;
}
return (T) scriptJavaClass;
}
use of org.python.core.PyObject in project oxCore by GluuFederation.
the class CustomScriptManager method createExternalTypeFromStringWithPythonException.
public BaseExternalType createExternalTypeFromStringWithPythonException(CustomScript customScript, Map<String, SimpleCustomProperty> configurationAttributes) throws Exception {
String script = customScript.getScript();
String scriptName = StringHelper.toLowerCase(customScript.getName()) + ".py";
if (script == null) {
return null;
}
CustomScriptType customScriptType = customScript.getScriptType();
BaseExternalType externalType = null;
InputStream bis = null;
try {
bis = new ByteArrayInputStream(script.getBytes("UTF-8"));
externalType = pythonService.loadPythonScript(bis, scriptName, customScriptType.getPythonClass(), customScriptType.getCustomScriptType(), new PyObject[] { new PyLong(System.currentTimeMillis()) });
} catch (UnsupportedEncodingException e) {
log.error(String.format("%s. Script inum: %s", e.getMessage(), customScript.getInum()), e);
} finally {
IOUtils.closeQuietly(bis);
}
if (externalType == null) {
return null;
}
boolean initialized = false;
try {
if (externalType.getApiVersion() > 10) {
initialized = externalType.init(customScript, configurationAttributes);
} else {
initialized = externalType.init(configurationAttributes);
log.warn(" Update the script's init method to init(self, customScript, configurationAttributes)", customScript.getName());
}
} catch (Exception ex) {
log.error("Failed to initialize custom script: '{}'", ex, customScript.getName());
}
if (initialized) {
return externalType;
}
return null;
}
use of org.python.core.PyObject in project atp by EdgeGallery.
the class TestCasePyExecutor method executeTestCase.
@Override
public void executeTestCase(TestCase testCase, String csarFilePath, TaskTestCase taskTestCase, Map<String, String> context) {
LOGGER.info("start call Python");
try {
Properties props = new Properties();
props.put("python.import.site", "false");
Properties preprops = System.getProperties();
PythonInterpreter.initialize(preprops, props, new String[0]);
PythonInterpreter interpreter = new PythonInterpreter();
interpreter.execfile(testCase.getFilePath());
PyFunction pyFunction = interpreter.get(EXECUTE, PyFunction.class);
PyObject pyobj = pyFunction.__call__(new PyString(csarFilePath), new PyString(context.toString()));
CommonUtil.setResult(pyobj, taskTestCase);
} catch (Exception e) {
LOGGER.error("python error. {}", e);
taskTestCase.setResult(Constant.FAILED);
taskTestCase.setReason("call python failed.");
}
}
Aggregations